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?
A lock_guard always holds a lock from its construction to its destruction. A unique_lock can be created without immediately locking, can unlock at any point in its existence, and can transfer ownership of the lock from one instance to another.
std::lock_guard A lock guard is an object that manages a mutex object by keeping it always locked. On construction, the mutex object is locked by the calling thread, and on destruction, the mutex is unlocked.
And that's why lock_guard isn't deprecated. scoped_lock and unique_lock may be a superset of functionality of lock_guard , but that fact is a double-edged sword. Sometimes it is just as important what a type won't do (default construct in this case).
No. The critical section begins at the point of declaration of the guard. The guard is declared after the condition - so it is not guarded. If you need the condition to be guarded as well, then move the guard before the if statement.
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. }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With