tags:

views:

80

answers:

1

I have a thread pool that is using shared mutexes from the boost library.

While the answers to my other question were helpful, http://stackoverflow.com/questions/3896717/example-of-how-to-use-boost-upgradeable-mutexes

What I have realised that what I actually need is not to block if a shared lock or upgrade lock could not be obtained. Unfortunately, the boost docs are lacking any examples of those in use.

Could someone please point me to or provide an example of specifically the shared_lock being used in this way.

i.e.

boost:shared_mutex mutex;

void thread()
{
    // try to obtain a scoped shared lock
    // How do I do that?
}

void thread2()
{
   // try to obtain a scoped upgrade lock 
   // and then a scoped unique lock
}
+1  A: 

The answer seems to be that you can provide boost:try_to_lock as a parameter to several of these scoped locks.

e.g.

boost::shared_mutex mutex;

// The reader version
boost::shared_lock<boost::shared_mutex> lock(mutex, boost::try_to_lock);
if (lock){
  // We have obtained a shared lock
}

// Writer version
boost::upgrade_lock<boost::shared_mutex> write_lock(mutex, boost::try_to_lock);
if (write_lock){
  boost::upgrade_to_unique_lock<boost::shared_mutex> unique_lock(write_lock);
  // exclusive access now obtained.
}

EDIT: I also found by experimentation that upgrade_to_unique_lock will fail if you don't have the upgrade lock. You can also do this:

boost::upgrade_to_unique_lock<boost::shared_mutex> unique_lock(write_lock);
if (unique_lock){
  // we are the only thread in here... safe to do stuff to our shared resource
}

// If you need to downgrade then you can also call
unique_lock.release();

// And if you want to release the upgrade lock as well (since only one thread can have upgraded status at a time)
write_lock.unlock().

Note: You have to call release followed by unlock or you'll get an locking exception thrown. You can of course just let unique_lock and write_lock go out of scope thereby releasing the locks, although I've found that sometimes you want to release it earlier and you should spend minimal time in that state.

Matt H