Mutual Exclusion (Mutex)

I learned about Mutual Exclusion (Mutex) from the <pthread.h> library. A mutex is a concurrency control mechanism that prevents multiple threads from accessing the same shared resource simultaneously, thus avoiding race conditions. The pthread library includes a function to 'lock' a thread, which needs to be initialized before accessing a thread. Then, the thread can acquire the mutex before accessing the shared resource. If another thread tries to acquire the mutex while the previous one still holds it, it will be blocked until the previous thread releases the mutex. This ensures that only one thread at a time can execute the part of the code that accesses the shared resource. It is important to release the mutex when the thread is done with its designated work; otherwise, the next thread will not be able to start.


The pthread_mutex_init() function is used to initialize a mutex.

  • The first argument is a pointer to a pthread_mutex_t variable.

  • The second argument is a pointer to a pthread_mutexattr_t variable.

  • The function returns 0 if the mutex is successfully initialized, otherwise, it returns an error code.

The pthread_mutex_lock() function is used to acquire a mutex.

  • The first argument is a pointer to a pthread_mutex_t variable.

  • The function returns 0 if the mutex is successfully acquired, otherwise, it returns an error code.

The pthread_mutex_unlock() function is used to release a mutex.

  • The first argument is a pointer to a pthread_mutex_t variable.

  • The function returns 0 if the mutex is successfully released, otherwise, it returns an error code.


Simple implementation of the mutex from pthread library:

#include <pthread.h>

static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void *pushButtonThread(void *value)
{
  pthread_mutex_lock(&lock);
  // do something...
  pthread_mutex_unlock(&lock);
  return NULL;
}

int main()
{
  pthread_t button[2];

  pthread_mutex_init(&lock, NULL);

  // Create as many thread as you need
  pthread_create(&button[0], NULL, &pushButtonThread, NULL);
  pthread_create(&button[1], NULL, &pushButtonThread, NULL);

  pthread_mutex_destroy(&lock);
  return 0;
}

Here is the documentation for the pthread mutex.

Last updated