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?
if (_mutex.try_lock()) { std::lock_guard<std::mutex> lock(_mutex, std::adopt_lock); }
(from stackoverflow.com/a/30457040) – Multure