Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Library initialization -- pthread_once in Win32 implementation

Hello. 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
}

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.

like image 838
Přemysl J. Avatar asked Dec 10 '22 21:12

Přemysl J.


2 Answers

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().

There is sample code here.

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
}
like image 115
i_am_jorf Avatar answered Jan 25 '23 23:01

i_am_jorf


You might want to check what pthreads-win32 does in its pthread_once() implementaion. or just use that, if that proves to be easier.

like image 31
Hasturkun Avatar answered Jan 25 '23 22:01

Hasturkun