Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a lock_guard with try_lock_for

I can use boost::lock_guard to acquire a lock on a boost::mutex object and this mechanism will ascertain that once the boost::lock_guard goes out of scope the lock will be released:

{
  boost::lock_guard<boost::mutex> lock(a_mutex);
  // Do the work
}

In this case, a_mutex will be released regardless of whether the code block was exited by an exception or not.

On the other hand, a boost::timed_mutex also supports a method try_lock_for(period), e.g.

if(a_timed_mutex.try_lock_for(boost::chrono::seconds(1))) {
  // Do the work
  a_timed_mutex.unlock(); // <- This is needed!
} else {
  // Handle the acquisition failure
}

This code will not unlock() the a_timed_mutex if the true block of the if statement is exited with an exception.

Question: Boost (and, as far as I can see, neither the C++11 standard) do not seem to offer a variant of lock_guard that works with try_lock() or try_lock_for(period). What is the "recommended" way or best practice to handle the second situation?

like image 959
user8472 Avatar asked Apr 19 '14 06:04

user8472


1 Answers

You can create the lock guard after locking, telling it to adopt the lock:

if(a_timed_mutex.try_lock_for(boost::chrono::seconds(1))) {
  boost::lock_guard<boost::mutex> lock(a_timed_mutex, boost::adopt_lock_t());
  // Do the work
} else {
  // Handle the acquisition failure
}

The standard lock_guard also allows this.

like image 195
Mike Seymour Avatar answered Oct 15 '22 22:10

Mike Seymour