Scoped Reader/Writer locks using Boost::thread

08 Dec 2008

The good news: boost::thread 1.37 has native reader/writer lock (they call them shared_mutex). The bad news: there is no scoped version of these, so you have to "manually" lock_shared, unlock_shared. Here's "scoped" versions of these

// this code is in public domain
// http://blog.modp.com/2008/12/scoped-readerwriter-locks-using.html

#include <boost/thread/shared_mutex.hpp>

class scoped_read_lock
{
private:
  boost::shared_mutex&  rwlock;
public:
  scoped_read_lock(boost::shared_mutex& lock)
    : rwlock(lock) { rwlock.lock_shared(); }
  ~scoped_read_lock() { rwlock.unlock_shared(); }  
};

class scoped_write_lock {
private:
  boost::shared_mutex& rwlock;
public:
  scoped_write_lock(boost::shared_mutex& lock)
    : rwlock(lock) { rwlock.lock(); }
  ~scoped_write_lock() { rwlock.unlock(); }
};

Usage:


boost::shared_mutex mylock.
...
...
{
scoped_reader_lock reader_lock(mylock);
// stuff...
// stuff...
} // unlocked automatically


Comment 2008-12-11 by None

Funny that you wrote about this cos I'm just hacking away at this on you know what. :)


Comment 2010-01-02 by None

Boost 1.35 and later have scoped versions of these as well... (see http://www.boost.org/doc/libs/1_40_0/doc/html/thread/synchronization.html#thread.synchronization.locks.shared_lock)

Code:
--------

/* The shared mutex /
boost::shared_mutex rwlock;

/
Acquire shared ownership. /
boost::shared_lock lock(rwlock);

/
Now holding shared ownership of rwlock. */

--------