Skip to content
Raymond Chen edited this page Jan 7, 2021 · 2 revisions

The re-entrant lock (CRITICAL_SECTION) wrapper is defined in wil/resource.h as part of the RAII resource wrappers library.

The WIL critical_section RAII class manages a CRITICAL_SECTION exposing appropriate locking methods:

// declare a lock:
wil::critical_section m_lock;

// Locks and unlocks when the returned variable goes out of scope
auto lock = m_lock.lock();

// Attempt to lock. If successful, the lock is released when the returned variable goes out of scope.
auto lock = m_lock.try_lock();
if (lock)
{
    // lock was successfully acquired by try_lock()...
}

// To release a lock before the returned variable goes out of scope use reset()
auto lock = m_lock.lock();
// My code...
lock.reset();

Though the need should be rare, if you have a raw CRITICAL_SECTION 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::EnterCriticalSection(&cs);
auto lock = wil::TryEnterCriticalSection(&cs);

Gotchas

Lock guard object

There are some gotchas in the use of the lock guard object returned by the lock() and try_lock() methods, and by the EnterCriticalSection and TryEnterCriticalSection functions. See Lock guard object for details.