pthread supports static initialization of pthread_mutex_t using PTHREAD_MUTEX_INITIALIZER.
Is it possible to achieve a similar static mechanism for mutex initialization using Windows mutex?
A mutex must be initialized (either by calling pthread_mutex_init(), or statically) before it may be used in any other mutex functions.
Use pthread_mutex_init(3THR) to initialize the mutex pointed at by mp to its default value ( mattr is NULL), or to specify mutex attributes that have already been set with pthread_mutexattr_init() . (For Solaris threads, see "mutex_init(3THR)".)
Mutex is a synchronization primitive that grants exclusive access to the shared resource to only one thread. If a thread acquires a mutex, the second thread that wants to acquire that mutex is suspended until the first thread releases the mutex.
Yes, this is possible with a few lines of code. Here is a port of pthread-compatible mutex operations, including a 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 the initialization to happen atomically when the lock is used the first time. If two threads enter the if-body, then only one succeeds in initializing the lock. Note that there is no need to CloseHandle() for the static lock's lifetime.
No, since Windows mutex are handles, they must be initialized with CreateMutex().
Note that the static initialization of pthread_mutex_t using PTHREAD_MUTEX_INITIALIZER is not a real init, it will be done internally at the first call to pthread_mutex_lock() or pthread_mutex_trylock()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With