-
Notifications
You must be signed in to change notification settings - Fork 236
Mutex handles
The unique_mutex
mutex handle wrapper is defined in wil/resource.h
as part of the RAII resource wrappers library.
It is a
unique_any
specialization that adds methods specific to the
typical needs of dealing with a mutex. There are three variants that can
be chosen based upon the error handling style the calling code desires.
// Create an empty unique_mutex.
wil::unique_mutex m1; // failures throw
wil::unique_mutex_nothrow m2; // failures return HRESULTs
wil::unique_mutex_failfast m3; // failures terminate
// Create during construction (not allowed with unique_mutex_nothrow)
wil::unique_mutex m4(L"MyMutexName");
// Standard operations:
m1.ReleaseMutex();
// Release the mutex when the object goes out of scope.
// Assumes that somebody else has already acquired the mutex.
auto releaseOnExit = m1.ReleaseMutex_scope_exit();
// Acquire the mutex oureselves,
// and release when going out of scope:
auto releaseOnExit = m1.acquire();
// Create or Open a mutex
m1.create();
m1.open(L"MyMutexName");
if (m1.try_create(L"MyMutexName")) {}
if (m1.try_open(L"MyMutexName")) {}
The constructor for unique_mutex
is unusual in
that passing a string creates a new mutex, behavior that is normally
the responsibility of a make_unique_xxx
-style function.
The expression unique_mutex(nullptr)
creates an empty
unique_mutex
, rather than a unique_mutex
containing an
freshly-created anonymous mutex. If you want the latter,
use unique_mutex((wchar_t*)nullptr)
or (better) explicitly
call the create()
method.
When dealing with mutex handles outside of unique_mutex
, WIL defines
some simple methods to emulate the same RAII patterns:
// Release the mutex when the returned value goes out of scope
auto releaseOnExit = wil::ReleaseMutex_scope_exit(handle);
There are some gotchas in the use of the lock guard object
returned by the ReleaseMutex_scope_exit()
and acquire()
methods.
See Lock guard object for details.