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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With