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

Hi Friends,

In this article, we shall solve the Readers & Writers problem.

Readers & Writers problem:

There may be m writers & n readers related to a shared data structure or a record in the database (some shared data). Only one writer thread can be updating the data, but there can be many readers accessing the data.

The constraints are:

1. Any number of readers can be accessing the data in critical section.
2. Only one writer thread should be allowed to update the data in critical section.

Solution:

int readers = 0; // Shared variable to keep track of number of readers,
                 // yes this also needs to be protected
Semaphore readersProtect = 1;
Semaphore roomEmpty = 1;

Writers thread code:

roomEmpty.wait();
    // Update shared data, critical section for writers
roomEmpty.signal();

Readers thread code:

readersProtect.wait();
    readers = readers + 1;
    if(readers == 1)
        roomEmpty.wait(); // First reader locks and bars writers
readersProtect.signal();

// Read shared data, critical section for readers

readersProtect.wait();
    readers = readers - 1;
    if(readers == 0)
        roomEmpty.signal();
        // Last reader unlocks and grants access to writers
readersProtect.signal();

The solution is very easy than it appears. roomEmpty is used to control entry for readers & writers. readersProtect is used to control access for readers shared variable which is accessed only by readers. Hence, it appears in readers thread code.

The writers code is simple. It waits on roomEmpty and if its free, the thread enters and updates the code, else it is queued up.

In readers code, we are increasing readers if any reader thread enters and decrease readers if it leaves. The first thread locks roomEmpty if it's not locked. Subsequent reader threads can just enter and read the data. Finally, the last reader unlocks or signals roomEmpty (that room is empty).

Go through the code slowly and it's easy to understand.

Till here, we have solved many problems using Mutex and Semaphore, but only pseudo code has been presented. In the subsequent articles, I am going to introduce real code related to Pthreads or POSIX threads.

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)