How to use a lock_guard with try_lock_for
Asked Answered
F

2

15

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?

Farfetched answered 19/4, 2014 at 6:58 Comment(0)
A
18

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.

Arana answered 19/4, 2014 at 8:1 Comment(0)
B
0

try unique_lock, unique_lock::try_lock_for()

Bistort answered 26/10, 2017 at 11:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.