Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reader/Writer Locks in C++

I'm looking for a good reader/writer lock in C++. We have a use case of a single infrequent writer and many frequent readers and would like to optimize for this. Preferable I would like a cross-platform solution, however a Windows only one would be acceptable.

like image 863
Matt Price Avatar asked Oct 28 '08 18:10

Matt Price


People also ask

What is read/write lock in C?

In many situations, data is read more often than it is modified or written. In these cases, you can allow threads to read concurrently while holding the lock and allow only one thread to hold the lock when data is modified. A multiple-reader single-writer lock (or read/write lock) does this.

What is reader/writer lock?

A readers/writer lock regulates access to a set of data. The readers/writer lock is so called because many threads can hold the lock simultaneously for reading, but only one thread can hold the lock for writing. Most device drivers do not use readers/writer locks. These locks are slower than mutexes.

How is read/write lock implemented?

Instead of having a single lock method, they have two - one for readers and one for writers. When readers enter the critical section they invoke the reader lock (and then reader unlock on exit); when writers enter the critical section they invoke the writer lock (and then writer unlock on exit).

What is the difference between reader/writer lock and normal lock?

The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive. So you can have many readers at a time, but only one writer - and the writer will prevent readers from reading, too.


2 Answers

Since C++ 17 (VS2015) you can use the standard:

#include <shared_mutex>

typedef std::shared_mutex Lock;
typedef std::unique_lock< Lock >  WriteLock;
typedef std::shared_lock< Lock >  ReadLock;

Lock myLock;

void ReadFunction()
{
     ReadLock r_lock(myLock);
     //Do reader stuff
}

void WriteFunction()
{
     WriteLock w_lock(myLock);
     //Do writer stuff
}

For older compiler versions and standards you can use boost to create a read-write lock:

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

typedef boost::shared_mutex Lock;
typedef boost::unique_lock< Lock >  WriteLock;
typedef boost::shared_lock< Lock >  ReadLock;
like image 141
Yochai Timmer Avatar answered Oct 24 '22 00:10

Yochai Timmer


Newer versions of boost::thread have read/write locks (1.35.0 and later, apparently the previous versions did not work correctly).

They have the names shared_lock, unique_lock, and upgrade_lock and operate on a shared_mutex.

like image 37
Greg Rogers Avatar answered Oct 23 '22 23:10

Greg Rogers