0Nicholas
0Nicholas

Reputation: 419

RAII locking with condition

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

Upvotes: 1

Views: 1293

Answers (2)

linuxsmiths
linuxsmiths

Reputation: 11

If you do not want to write another function you can use a dummy lock like this. Note that acquiring the dummy lock is inconsequential as it's a local variable.

 std::shared_mutex dummy_lock;
 std::shared_lock<std::shared_mutex> lock(
    acquire_lock ? original_lock : dummy_lock);

Upvotes: 0

NathanOliver
NathanOliver

Reputation: 180955

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

Upvotes: 6

Related Questions