Yes, it is possible with a few lines of code. Here is the port of pthread compatible mutex operations, including the static initializer MUTEX_INITIALIZER that you want:
#define MUTEX_TYPE HANDLE #define MUTEX_INITIALIZER NULL #define MUTEX_SETUP(x) (x) = CreateMutex(NULL, FALSE, NULL) #define MUTEX_CLEANUP(x) (CloseHandle(x) == 0) #define MUTEX_LOCK(x) emulate_pthread_mutex_lock(&(x)) #define MUTEX_UNLOCK(x) (ReleaseMutex(x) == 0) int emulate_pthread_mutex_lock(volatile MUTEX_TYPE *mx) { if (*mx == NULL) { HANDLE p = CreateMutex(NULL, FALSE, NULL); if (InterlockedCompareExchangePointer((PVOID*)mx, (PVOID)p, NULL) != NULL) CloseHandle(p); } return WaitForSingleObject(*mx, INFINITE) == WAIT_FAILED; }
Basically, you want initialization to be performed atomically when the lock is used for the first time. If two threads enter the if body, then only one lock is initialized. Note that there is no need for CloseHandle () for the static lock time.
Dr. Alex RE
source share