Synchronization primitives: Mutex and Semaphore - Article 4

In this article, lets deep dive and understand the synchronization primitives - Mutex and Semaphore.

Mutex or Mutual Exclusion is the basic form of synchronization primitive. Its a locking mechanism and ensures that only one thread or process can enter the critical section. After finishing the work (Like updating global variable or a data structure), the thread unlocks the mutex.

NOTE: Mutex is used to synchronize threads. However, latest addition to POSIX standard says that the mutex can be used to synchronize processes if it's shared between them.

A real world example follows: In olden days when there were no mobile phones, love birds (I mean lovers) used the STD phone booth extensively. What would they do? enter the phone booth, lock it and dial their partners home phone and start off on a long call - Outside, you could see a long line of people cursing the guy inside and waiting to get into the booth.

i.e., one and only thread or process (Person) needs to enter critical section (Phone booth), lock the mutex (Lock the booth), process the data (Call the partner) and unlock and leave the critical section (Hang up phone and come out of the booth).

Similarly, the other threads trying to lock the mutex are added to the wait Q. After the mutex is unlocked, one thread or all the threads may be woken up by the scheduler in OS which is implementation dependent.

This is the pseudo code for mutex:

// Declare a mutex
Mutex OnlyOneThread;

// Share the mutex between say 5 threads

OnlyOneThread.lock();
    // Critical section code here like updating a shared linked list
OnlyOneThread.unlock();

Semaphore is a signalling mechanism which can be used for serialization.

For example, you and your friend are planning to go for a movie and your friend will say to you to leave only after he/she calls you.

The pseudo code is like below:

Your friend:

Leave to Movie;
Call to signal;

You:

Wait for call;
Leave to Movie;

i.e., You don't leave to movie until you get a call from your friend.

Whatever we have seen is just the tip of the ice berg. In the next article, we shall go further deep and see how exactly Semaphore is implemented and how it can be used to solve serialization problems.

Comments

Popular posts from this blog

Synchronization primitives: Mutex and Semaphore (Serialization & Mutex problems using Semaphore) - Article 6

Synchronization: Discussion about Mutex and Semaphore - Article 1

Copy constructor in C++ (Part 2)