如何保护基于C的库的init函数?

我已经编写了一个基于C的库,并且它可以并行地在multithreading中工作,我在init函数中创建了一些全局互斥。

我希望在multithreading中使用库API之前,可以在主线程中调用init函数。

但是,如果直接在multithreading中调用init函数本身,那么这是一个问题。 有没有办法保护我的库中的init函数本身? 我能想到的一种方法是让应用程序创建一个互斥锁并保护对我的init函数的并行调用,但是我可以保护它免受我的库本身的影响吗?

您可能想要使用默认入口点函数。

在Windows中,您可以使用DllMain来创建和销毁您的互斥锁。

在Linux和其他一些Unix上,您可以在进入和退出函数上使用__attribute__((constructor))__attribute__((destructor))

在这两种情况下,函数将在加载和卸载时调用一次

POSIX具有pthread_once函数

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

在linux手册页中,他们有以下有用的示例

 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. */ }