Mutual Exclusion or, more commonly, MutEx is a naive way to share memory between threads.


Operation

Mutexes operate by only allowing access to a location by a single thread at once.

This is enforced by the presence of a “lock” which is readable by other threads and tells them which thread “owns” the memory location currently and if it is safe to write or not.

This can, however, slow down the program a lot as it cannot be properly parallel due to many threads waiting on others to complete. Instead, the Producers and Consumers approach may be used.


API

Create a mutex with:

  • pthread_mutex_t m = ... produces a static variable
  • prthread_mutex_init() dynamically create a mutex at runtime

Lock/Unlock a mutex with:

  • pthread_mutex_lock() lock the mutex to only allow writes from the current thread, or wait for another thread to finish with the mutex
  • pthread_mutex_try_lock() attempt lock the mutex only if it is free, if not do something else
  • pthread_mutex_unlock() unlock the mutex to allow other threads to take it