Search code examples
c++lockingstdmutexraii

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?


Solution

  • 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
    }