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

Hi Friends,

In the previous articles, we have gained knowledge about Mutex and Semaphore. In this article, we shall see how a Semaphore can be used to solve serialization problem and Mutual Exclusion (Mutex) problem.

Serialization problem:

Thread 1:

Event A; // Could be any code

Thread 2:

Event B; // Could be any code

The problem is, we have to ensure that Event B or a particular code or instructions should always be executed after Event A or some other particular code. Basically, we are serializing the instructions irrespective of how the threads are scheduled to run.

Solution:

There are no resources here, we need to just signal, initialize Semaphore to 0.

Semaphore SignalThread2 = 0;

Thread 1:

Event A;
SignalThread2.signal();

Thread 2:

SignalThread2.wait();
Event B;

The code for Thread 1 and Thread 2 is as above. Irrespective of which thread is scheduled, Event A always occurs before Event B. How? Let's say Thread 2 is scheduled first, it executes wait() and waits for Thread 1's signal, only then it proceeds. Check the semaphore code in previous article to understand better.

Now, let's solve Mutual Exclusion problem using Semaphore.

Solution:

Initialize Semaphore to 1 as we need to provide exclusive access to the code, this is similar to saying there is 1 resource.

Semaphore MutexSemaphore = 1;

Thread 1:

MutexSemaphore.wait_if_locked_else_proceed(); // MutexSemaphore.wait();
// Execute critical section code
MutexSemaphore.signal_done(); // MutexSemaphore.signal();

Thread 2:

MutexSemaphore.wait_if_locked_else_proceed(); // MutexSemaphore.wait();
// Execute critical section code
MutexSemaphore.signal_done(); // MutexSemaphore.signal();

Don't be confused with the above solution and functions. They are all same: wait(), decrement(), you can call it by any name, but the operation is same. Whichever thread comes first proceeds, but if it's put to sleep while in critical section and another thread is scheduled, it can't decrement because the semaphore value is 0, it waits. Once the other thread is scheduled to run and it signals (or increments), the waiting thread enters the critical section.

I suggest to read the previous article and this article together to understand the solutions better.

Comments

Popular posts from this blog

Synchronization primitives: Mutex and Semaphore (Readers & Writers problem) - Article 8

Copy constructor in C++ (Part 2)