Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 933
Jay Avatar asked Aug 24 '10 11:08

Jay


People also ask

Do mutexes need to be initialized?

A mutex must be initialized (either by calling pthread_mutex_init(), or statically) before it may be used in any other mutex functions.

How do you initialize mutex?

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)".)

What is mutex in multithreading?

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.


2 Answers

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.

like image 122
Dr. Alex RE Avatar answered Oct 16 '22 22:10

Dr. Alex RE


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

like image 37
CharlesB Avatar answered Oct 16 '22 23:10

CharlesB