stwykd
stwykd

Reputation: 2884

How to tighten the scope when using C++ lock_guard?

In C++, lock_guard allows you to be RAII compliant when using locks. It calls lock() when constructing the lock_guard, and unlock() when destroying it once it goes out of scope.

Is it possible to tighten the scope of lock_guard such that it is destroyed sooner, to avoid keeping the lock for longer than necessary?

Upvotes: 2

Views: 1219

Answers (2)

stwykd
stwykd

Reputation: 2884

A unique_lock guard can be used instead of lock_guard. unique_lock gives you same RAII guarantees as lock_guard (calls lock() when constructing the lock_guard, and unlock() when destroying), as well as exposing lock() and unlock() to allow the you to lock and unlock yourself.

With a unique_lock you can lock() before the critical path, and unlock() straight after.

unique_lock will only call unlock() in the destructor if the lock was previously acquired, therefore there's no risk of releasing the lock twice (which causes undefined behavior).

Upvotes: 0

Lukas-T
Lukas-T

Reputation: 11340

I'm not 100% sure what you mean, but you can introduce a block scope for the std::lock_guard with curly braces like this:

void foo()
{
    // do uncritical stuff

    { 
        // critical part starts here with construction
        std::lock_guard<std::mutex> myLock(someMutex);

        // do critical stuff
    } // critical parts end here with myLock going out of scope

    // do uncritical stuff
}

Upvotes: 6

Related Questions