views:

63

answers:

2

I have written a C based library and for it to work in multi-thread parallely, I create some global mutexes in the init function.

I expect the init function to be called in the main thread before the library APIs are used in multi-thread.

But, if the init function itself is called in multi-thread directly, then it is a problem. Is there a way to protect the init function itself from my library? One way I can think of is to ask the application to create a mutex and protect parallel calls to my init function, but can I protect it from my library itself?

+4  A: 

You probably want to use teh default entry point functions.

In windows you can use DllMain to create and destroy your mutexes.

On Linux and probably some other Unixes you can use __attribute__((constructor)) and __attribute__((destructor)) on your entry and exit functions.

In both these case, the functions will be called once on load and unload

doron
Can these be used only with dlopen or will this work even if we link the dynamic library using -l option to the application?
Jay
This seems to be GCC Specific option. I have an application in which the library will be linked using -l option and the same library will be loaded using dlopen also. What will happen in that case? Will the constructor be called twice?
Jay
I think the answer is yes. Constructor and Destructor work for standard executables as well. See http://gcc.gnu.org/onlinedocs/gcc-4.5.0/gcc/Function-Attributes.html#Function-Attributes
doron
+2  A: 

POSIX has the pthread_once function

int pthread_once(pthread_once_t *once_control,
              void (*init_routine)(void));

In the linux man page they then have the following instructive example

static pthread_once_t random_is_initialized = PTHREAD_ONCE_INIT;
extern int initialize_random();

int random_function()
{
 (void) pthread_once(&random_is_initialized, initialize_random);
              ... /* Operations performed after initialization. */
}
Jens Gustedt