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

时间:2010-08-24 11:12:59

标签: c synchronization

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

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

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

2 个答案:

答案 0 :(得分:5)

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

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

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

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

答案 1 :(得分:2)

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