库初始化 - 调用pthread_once在Win32中的实现 [英] Library initialization -- pthread_once in Win32 implementation
问题描述
我试图让我的图书馆完全线程安全的初始化函数,我无法很容易地找到替代调用pthread_once,这应该很容易解决的问题。我来这个code:
I am trying to make a fully thread-safe initialization function for my library and I couldn't easily find an alternative to pthread_once, which should solve the problem very easily. I've come to this code:
void libInit (void)
{
#ifdef WIN32
static volatile int initialized = 0;
static HANDLE mtx;
if (!initialized)
{
if (!mtx)
{
HANDLE mymtx;
mymtx = CreateMutex(NULL, 0, NULL);
if (InterlockedCompareExchangePointer(&mtx, mymtx, NULL) != NULL)
CloseHandle(mymtx);
}
WaitForSingleObject(mtx);
if (!initialized)
{
libInitInternal();
initialized = 1;
}
ReleaseMutex(mtx);
}
#else
static pthread_once_t initialized = PTHREAD_ONCE_INIT;
pthread_once(&initialized, libInitInternal);
#endif
}
的 libInitInternal()
调用导致线程安全的功能,即初始化库。
The libInitInternal()
call leads to a thread-unsafe function, that initializes the library.
我想听听你知道一个更好的解决方案是什么我可能做错了,或者是否有任何建议。
I would like to hear any suggestions on what I could be doing wrong or whether you know about a better solution.
推荐答案
我想你想使用的一次性初始化功能。在同步模式,所有线程阻塞,直到第一个线程调用它完成。似乎类似于调用pthread_once()。
I think you want to use the One-Time Initialization functionality. In synchronous mode, all threads block until the first thread to call it completes. Seems analogous to pthread_once().
有 code这里。
所以你的情况,你会说:
So in your case, you would say:
BOOL CALLBACK CallLibInitInternal(PINIT_ONCE InitOnce, PVOID Parameter, PVOID *lpContex) {
libInitInternal();
return TRUE;
}
void libInit() {
#ifdef WIN32
static INIT_ONCE s_init_once;
InitOnceExecuteOnce(&s_init_once, CallLibInitInternal, NULL, NULL);
#else
...
#endif
}
这篇关于库初始化 - 调用pthread_once在Win32中的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!