C++: Mutex

Bjarne-stroustrup
 


A mutex (abbreviated Mutually Exclusive access) is a synchronization object, a variant of semaphore with k=1. A mutex is said to be seized by a task decreasing k. It is released when the task restores k. Mutexes are typically used to protect a shared resource from concurrent access. A task seizes (or acquires) the mutex, then accesses the resource, and after that releases the mutex.

A mutex is a low-level synchronization primitive exposed to deadlocking. A deadlock can occur with just two tasks and two mutexes (if each task attempts to acquire both mutexes, but in the opposite order). Entering the deadlock is usually aggravated by a race condition state, which leads to sporadic hangups, which are very difficult to track down.

Win32

Works with: Win32

To create a mutex operating system “object”:

HANDLE hMutex = CreateMutex(NULL, FALSE, NULL);

To lock the mutex:

WaitForSingleObject(hMutex, INFINITE);

To unlock the mutex

ReleaseMutex(hMutex);

When the program is finished with the mutex:

CloseHandle(hMutex);

POSIX

Works with: POSIX

Creating a mutex:

#include <pthread.h>
 
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

Or:

pthread_mutex_t mutex;
pthread_mutex_init(&mutex, NULL);

Locking:

int error = pthread_mutex_lock(&mutex);

Unlocking:

int error = pthread_mutex_unlock(&mutex);

Trying to lock (but do not wait if it can’t)

int error = pthread_mutex_trylock(&mutex);

SOURCE

Content is available under GNU Free Documentation License 1.2.