How to use lock_guard with try_lock_for

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); // Do the work } 

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?

+7
c ++ boost boost-mutex
source share
2 answers

You can create lock protection after a lock by telling it to accept 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.

+10
source share

try unique_lock, unique_lock :: try_lock_for ()

-one
source share

All Articles