Use std::lock_guard with try_lock

Mr. Anderson picture Mr. Anderson · Nov 29, 2015 · Viewed 10.9k times · Source

Is there a way I can tell std::lock_guard to call try_lock instead of lock when it acquires the mutex?

The only way I could think of is to use std::adopt_lock:

if (!_mutex.try_lock())
{
    // Handle failure and return from the function
}
std::lock_guard<my_mutex_class> lock(_mutex, std::adopt_lock);

Is there a built-in solution for my problem rather then acquiring the lock explicitly and then give lock_guard the responsibility for releasing it?

Answer

T.C. picture T.C. · Nov 29, 2015

A basic design invariant of lock_guard is that it always holds the lock. This minimizes the overhead since its destructor can unconditionally call unlock(), and it doesn't have to store extra state.

If you need the try-to-lock behavior, use unique_lock:

std::unique_lock<std::mutex> lock(_mutex, std::try_to_lock);
if(!lock.owns_lock()){
    // mutex wasn't locked. Handle it.
}