Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
290 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...