I can use boost::lock_guard to get the lock of the boost::mutex object, and this mechanism will establish that after exiting the boost::lock_guard lock will be released:
{ boost::lock_guard<boost::mutex> lock(a_mutex);
In this case, a_mutex will be released regardless of whether the code block was excluded due to the exception or not.
On the other hand, a boost::timed_mutex also supports the try_lock_for(period) method, for example.
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() a_timed_mutex if the true block of the if completes with an exception.
Question: Boost (and, as far as I can see, neither the C ++ 11 standard) seems to offer a lock_guard option that works with try_lock() or try_lock_for(period) . What is the βrecommendedβ method or best practice for solving the second situation?
c ++ boost boost-mutex
user8472
source share