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.
}