Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple-readers, single-writer locks in Boost

I'm trying to implement the following code in a multithreading scenario:

Get shared access to mutex
Read data structure
If necessary:
   Get exclusive access to mutex
   Update data structure
   Release exclusive lock
Release shared lock

Boost threads has a shared_mutex class which was designed for a multiple-readers, single-writer model. There are several stackoverflow questions regarding this class. However, I'm not sure it fits the scenario above where any reader may become a writer. The documentation states:

The UpgradeLockable concept is a refinement of the SharedLockable concept that allows for upgradable ownership as well as shared ownership and exclusive ownership. This is an extension to the multiple-reader / single-write model provided by the SharedLockable concept: a single thread may have upgradable ownership at the same time as others have shared ownership.

From the word "single" I suspect that only one thread may hold an upgradable lock. The others only hold a shared lock which can't be upgraded to an exclusive lock.

Do you know if boost::shared_lock is useful in this situation (any reader may become a writer), or if there's any other way to achieve this?

like image 441
Amnon Avatar asked Nov 17 '10 10:11

Amnon


1 Answers

Yes, you can do exactly what you want as shown in the accepted answer here. A call to upgrade to exclusive access will block until all readers are done.

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
}
like image 187
Steve Townsend Avatar answered Sep 20 '22 12:09

Steve Townsend