Monday 30 January 2012

Thread and process synchronisation with mutex

In my previous article I described how to use semaphore in order to synchronise threads or processes. Mutex is a semaphore specialisation and can be used in the special case - when only one thread (or process) is allowed to access shared resource.

Mutex is a synchronisation object that controls resource access (critical section execution) by maintaining the knowledge of its current owner (accessor - thread or process). Mutex strictly limits access to a single accessor at a time.

Ownership over the mutex is controlled with following operations:
  • acquire() (or lock()) - passes the ownership of the mutex to the calling thread
  • release() (or unlock()) - calling thread gives up its ownership of mutex. Only thread that acquired the mutex can release it

Mutex has two states:
  • signalled - when no thread owns it; acquire() does not block
  • non-signalled - when owned by some thread; acquire() in other thread blocks till mutex gets signalled

When Thread1 acquires ownership of mutex, it has a exclusive right to access the shared resource (to execute the code in the critical section). Once it's finished, it needs to release mutex so another thread can acquire ownership and access the resource. If thread does not release the mutex, other threads cannot acquire it and application is in a deadlock. It is therefore very important to make sure that mutex is released under any condition, no matter of the outcome of the code in the critical section! RAII-compliant design can prevent program's execution to leave critical section's scope without releasing the mutex.

Semaphore behaves like shared mutex with a count controlled by multiple threads that are allowed to access shared resource. Mutex is stricter, only thread that owns it has the power to release it, and only that thread can access shared resource.

The following example shows how to use mutex in order to synchronise processes that write into the shared file (problem described in this article):

main.cpp:



Links and References:

Mutex Objects (MSDN)
Using Mutex Objects (MSDN)
Mutual exclusion (Wikipedia)

No comments: