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?