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?
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
}
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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.