-
Notifications
You must be signed in to change notification settings - Fork 241
Reader writer locks
Raymond Chen edited this page Jan 7, 2021
·
2 revisions
The reader-writer lock (SRWLOCK) wrapper is defined in wil/resource.h
as part of the RAII resource wrappers library.
The WIL srwlock
RAII class manages an SRWLOCK
exposing appropriate locking methods:
// declare a lock:
wil::srwlock m_lock;
// Locks and unlocks when the returned variable goes out of scope
auto lock = m_lock.lock_exclusive(); // or 'lock_shared' for a shared lock
// Attempt to lock. If successful, the lock is released when the returned variable goes out of scope.
auto lock = m_lock.try_lock_exclusive(); // or 'try_lock_shared' for a shared lock
if (lock)
{
// lock was successfully acquired by try_lock_exclusive()...
}
// To release a lock before the returned variable goes out of scope use reset()
auto lock = m_lock.lock_exclusive(); // or 'lock_shared' for a shared lock
// My code...
lock.reset();
Though the need should be rare, if you have a raw SRWLOCK
without the
WIL class, you can use the same locking mechanisms (return of an RAII
class) through methods named identically to the system counterparts in
the wil
namespace:
auto lock = wil::AcquireSRWLockExclusive(&rwlock);
auto lock = wil::AcquireSRWLockShared(&rwlock);
auto lock = wil::TryAcquireSRWLockExclusive(&rwlock);
auto lock = wil::TryAcquireSRWLockShared(&rwlock);
There are some gotchas in the use of the lock guard object
returned by the lock_xxx()
and try_lock_xxx()
methods, and by
the AcquireXxx
and TryAcquireXxx
functions.
See Lock guard object for details.