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

Re: global variables in shared libraries



In article <[🔎] 20040122223439.GA26576@piper.madduck.net>,
martin f krafft  <madduck@debian.org> 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.
>
>However, what happens when I have a threaded process us the library?

Threads share memory space, so they share the variable.

If the variable needs to be per-thread (like, say, "errno")
it is a bit hard. The simplest (well..) thing to do is to
add a "register" function to your library, that takes a
pointer to a function returning the address of a variable.

Then your application code does:

int	globalvar;

void *globalvar_address(char *name)
{
	if (strcmp(name, "somevar") == 0)
		return &globalvar;
	return NULL;
}

main()
{
	yourlib_register_callback(globalvar_address);
}

The library does something like:

static void *(*lib_funptr)(char *name);

void yourlib_register_callback(void *(*arg)(char *))
{
	lib_funptr = arg;
}

void somefunc_in_lib(int argh)
{
	int	*globalvar = NULL;

	if (lib_funptr && (globalvar = (*lib_funptr)("somevar")) != NULL)
		*globalvar = 5;
}

Now, the application provides a function that returns the
address of the global variable. For threads, this function can
return a different address for each thread using thread
private data.

Mike.



Reply to: