Skip to content
Search

Readers–writer lock

lastmod 2018-08-17created 2015-10-048 edits

A Reader-Writer Lock (hereafter RW lock) is similar to a Mutex but provides a higher degree of parallelism. A Mutex has only two states (lock and unlock) and only one thread can hold the lock at a time, whereas an RW lock has three states (read-lock, write-lock, unlock). Only one thread at a time can hold a write-lock, but multiple threads can hold a read-lock at the same time.

While a write-lock is held, all threads attempting to lock are blocked until the lock is released. While a read-lock is held, threads attempting a read-lock can acquire it, but a thread attempting a write-lock is blocked until every thread holding the lock releases it. It may differ depending on how the RW lock is implemented, but generally, if there is a thread blocked waiting to acquire a write-lock, threads that subsequently attempt a read-lock are blocked. Otherwise, the thread waiting to acquire the write-lock could remain blocked forever.

While a write-lock is held, only one thread can access the data; while a read-lock is held, multiple threads can access the data. Therefore, an RW lock is effective when the data protected by the lock is read more often than it is modified.

Readers–writers problem

In computer science, the readers-writers problem is a problem that arises when multiple readers and writers share and access a single storage space (buffer). Readers read data from the shared space. Multiple readers can read data at the same time. Writers write data to the shared space. While a writer is writing data to the shared space, only that writer has access, and other readers and writers cannot access it.

Boost version

#include <boost/thread/locks.hpp>
#include <boost/thread/shared_mutex.hpp>

boost::shared_mutex _access;

void reader()
{
  // get shared access
  boost::shared_lock<boost::shared_mutex> lock(_access);

  // now we have shared access
}

void writer()
{
  // get upgradable access
  boost::upgrade_lock<boost::shared_mutex> lock(_access);

  // get exclusive access
  boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
  // now we have exclusive access
}

See also

Favorite site