Reputation: 14980
For a certain project,I have to use the static mutex initializer in pthread.However my library is supposed to be portable on Windows as well.
pthread_mutex_t csapi_mutex = PTHREAD_MUTEX_INITIALIZER;
Is there a corrosponding static initializer on windows.?
Thanks.
Upvotes: 1
Views: 4441
Reputation: 1698
I came up with this port of pthread-compatible mutex operations:
#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.
Upvotes: 2
Reputation: 57774
Pthreads-win32 should provide very good support for such constructs. But I have not checked.
Upvotes: 4