Jay
Jay

Reputation: 24895

Is it possible to do static initialization of mutexes in Windows?

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?

Upvotes: 6

Views: 3359

Answers (2)

Dr. Alex RE
Dr. Alex RE

Reputation: 1698

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.

Upvotes: 9

CharlesB
CharlesB

Reputation: 90306

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

Upvotes: 2

Related Questions