Is it possible to statically initialize mutexes in Windows?

pthread supports pthread_mutex_t static initialization using PTHREAD_MUTEX_INITIALIZER.

Is it possible to create a similar static mechanism for initializing a mutex using a Windows mutex?

+6
windows pthreads mutex
source share
2 answers

No, since Windows mutexes are descriptors, they must be initialized using CreateMutex() .

Please note that pthread_mutex_t static initialization using PTHREAD_MUTEX_INITIALIZER not a real init, it will be executed internally the first time pthread_mutex_lock() or pthread_mutex_trylock() called

+2
source share

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) /* static initializer? */ { 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.

+7
source share

All Articles