I have a piece of code which needs to be protected by a lock only if some condition is true.
if(condition) {
std::lock_guard<std::mutex> guard(some_mutex);
// do a bunch of things
} else {
// do a bunch of things
}
Although I can move all of the // bunch of things
in a separate function and call that, I was wondering if there is an RAII way that would allow to take the lock conditionally.
Something like
if(condition){
// the lock is taken
}
// do a bunch of things
// lock is automatically released if it was taken
CodePudding user response:
You can switch to using a std::unique_lock
and use its std::defer_lock_t
tagged constructor. This will start with the mutex unlocked, but you can then use its lock()
method to lock the mutex, which will then be released by the destructor. That would give you a code flow that looks like this:
{
std::unique_lock<std::mutex> guard(some_mutex, std::defer_lock_t{});
if (mutex_should_be_locked)
{
guard.lock();
}
// rest of code
} // scope exit, unlock will be called if the mutex was locked