Hello. I am trying to make a fully thread safe initialization function for my library, and I could not easily find an alternative to pthread_once, which should solve the problem very easily. I came 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 }
A call to libInitInternal() results in an unsafe function that initializes the library.
I would love to hear any suggestions on what I might do wrong, or you know about a better solution.
source share