> For the complete documentation index, see [llms.txt](https://astranebula.gitbook.io/blog/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://astranebula.gitbook.io/blog/software-engineering/mutual-exclusion-mutex.md).

# 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:

```c
#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.](https://chrisdedman.vercel.app/blog/articles/pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_init.html)
