[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: global variables in shared libraries



-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Thursday 22 January 2004 23:34, martin f krafft wrote:
> If I use a global variable in a shared library, is it shared among
> all instances using that library? Here, I would say no because
> a process' memory space is separate from another's.

Right.

> However, what happens when I have a threaded process us the library?

A process is a memory-space, which is shared by all its threads. Therefore, 
all threads see the same vars.

> The first is to expect the user to instantiate a struct, e.g.
> a struct global_settings and pass it along to each function of the
> API. This is cumbersome but would work, although I could not be
> assured that it's always the same instantiation -- the user could
> create two objects and pass them alternatingly, thereby messing with
> the integrity of the global settings and the library code. It is
> questionable whether I should guard against such a case, but I feel
> like it ;^>.
>
> The other approach seems cleaner: I declare "extern" variables in
> the interface and expect the user to instantiate them, while I use
> them freely in the code. The problem here is that the user would
> have to do so on a global level in his/her code, so we'd have the
> same problem again, albeit the responsibility would be shifted from
> the library to the user code. I am not sure this is preferable.
>
> I'd be interested to hear your opinions, and how you deal with these
> challenges.

Hmmm, this is really a thing that needs to be decided case-by-case. Anyhow, a 
third method is to have global vars that are TLS (Thread Local Storage). This 
still wont work if one thread needs more than one set of settings, but it is 
rare that one needs to (Well, it still depends on the particular lib you're 
writing).

happy hacking

Uli
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.2 (GNU/Linux)

iD8DBQFAEGa6wVdGSYi8Mq8RAkUOAJ0Vq1CjDQ4u7ThbLt6jAcCUFd8p8gCfRleK
4ozOUXejvCjARPhZEO7sy4c=
=fu/Y
-----END PGP SIGNATURE-----



Reply to: