I am new to C++11 threading.
The following piece of code should be executed only by the first thread.
The other threads (which might race with the first thread) should not enter the locked code area (that's why the std::try_lock()
is there).
std::mutex mu;
// now ensure this will get called only once per event
if (std::try_lock(mu) != -1)
{
return;
}
{
std::lock_guard<std::mutex> guard(mu);
// critical section
} // mutex will be unlocked here
(Outside from writing my own lock_guard) Is there a way to use a similar & standard std::lock_guard
variant, but which will take my !locked! mutex (effect of std::try_lock()
above) and simply unlock it when the d-tor of that guard will be called?