How to protect C library init function?

I wrote a C-based library and to make it work in multi-threaded parallel mode, I create some global mutexes in the init function.

I expect the init function to be called in the main thread until the library APIs are used in multithreaded mode.

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

+2
source share
2 answers

You probably want to use the default entry point functions.

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

On Linux, and possibly some other Unix applications, you can use __attribute__((constructor)) and __attribute__((destructor)) for your entry and exit functions.

In both cases, the functions will be called once during loading and unloading.

+5
source

POSIX has the pthread_once function

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

On the Linux manual page, they 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. */ } 
+2
source

All Articles