educative.io

Reader-Writer Locks - Operating Systems: Virtualization, Concurrency &

In the reader writer chapter, in the below code:

void rwlock_acquire_readlock(rwlock_t *rw) {
sem_wait(&rw->lock);
rw->readers++;
if (rw->readers == 1) // first reader gets writelock
sem_wait(&rw->writelock);
sem_post(&rw->lock);
}

We are using binary semaphore for read lock, How multiple readers are allowed at the same time?

Hello @Dilip,
In the provided code, it may seem counterintuitive that multiple readers are allowed at the same time when using a binary semaphore (which traditionally allows only one thread to access a shared resource at a time). However, the key to understanding how multiple readers are allowed lies in the logic surrounding the binary semaphore and the reader count (readers ).

Now, let’s analyze how this logic allows multiple readers to access the shared resource at the same time:

  • The binary semaphore lock ensures that only one thread at a time can enter the critical section where the readers count is updated. This prevents race conditions and ensures that the readers count is updated correctly.
  • When the first reader arrives (rw->readers == 1), it will acquire the writelock, preventing any writer from accessing the shared resource. This guarantees that when a writer is present, no other readers can enter simultaneously.
  • However, if multiple readers arrive after the first reader, they will not proceed to acquire the writelock, as the condition rw->readers == 1 will not be satisfied. Instead, they will directly proceed to increment the readers count and then release the lock.
  • Since the readers only need to update the readers count, which does not require mutual exclusion, they can access the shared resource (read lock) simultaneously.

In summary, while a binary semaphore is used to protect the critical section where the readers count is updated, multiple readers are allowed at the same time due to the conditional logic surrounding the write lock acquisition. The first reader arriving will acquire the write lock, but subsequent readers will not, allowing them to read concurrently. This approach ensures that multiple readers can read concurrently while also providing exclusive access to writers when needed.

I hope this helps. Happy Learning :slight_smile:

1 Like

Thanks @Komal_Arif that was helpful. Really appreciate your response.

1 Like