Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use std::lock_guard with try_lock

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?

like image 619
Mr. Anderson Avatar asked Nov 29 '15 08:11

Mr. Anderson


People also ask

What is the difference between unique_lock and lock_guard?

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.

What is the role of std :: lock_guard?

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.

Are lock guards deprecated?

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

Does std :: lock_guard block?

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.


1 Answers

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. } 
like image 53
T.C. Avatar answered Oct 08 '22 20:10

T.C.