Temporarily Dropping a Lock: The Anti-lock Pattern -- Raymond Chen
In C++, it's common to use RAII types like std::lock_guard
to manage synchronization primitives, ensuring a lock is acquired at object creation and released at destruction. However, a less common but useful pattern is the "anti-lock," which temporarily releases a lock and reacquires it later, useful in scenarios where you need to drop a lock while performing certain operations, like calling out to other components to avoid deadlocks.
Temporarily Dropping a Lock: The Anti-lock Pattern
by Raymond Chen
From the article:
There is a common pattern in C++ of using an RAII type to manage a synchronization primitive. There are different versions of this, but they all have the same basic pattern:
- Creating the object from a synchronization object: Locks the synchronization object.
- Destructing the object: Unlocks the synchronization object.
These types go by various names, like
std::
,lock_ guard std::
, orunique_ lock std::
, and specific libraries may have versions for their own types, such as C++/WinRT’scoped_ lock winrt::
and WIL’sslim_ lock_ guard wil::
(which you thankfully never actually write out; just userwlock_ release_ exclusive_ scope_ exit auto
).One thing that is missing from most standard libraries, however, is the anti-lock.
The idea of the anti-lock is that it counteracts an active lock.