From 44f418491521d395c6877ad2faad2c5f21c86571 Mon Sep 17 00:00:00 2001 From: Raymond Chen Date: Mon, 24 Aug 2020 07:47:02 -0700 Subject: [PATCH] Split out from main resource.h wiki page, which is getting too long --- Semaphore-handles.md | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Semaphore-handles.md diff --git a/Semaphore-handles.md b/Semaphore-handles.md new file mode 100644 index 0000000..aafdc7c --- /dev/null +++ b/Semaphore-handles.md @@ -0,0 +1,41 @@ + +The `unique_semaphore` semaphore handle wrapper is defined in `wil/resource.h` +as part of the [[RAII resource wrappers]] library. +It is a +[[unique\_any|RAII resource wrappers#wilunique_any]] +specialization that adds methods specific to +the typical needs of dealing with a semaphore. There are three variants +that can be chosen based upon the error handling style the calling code +desires. + +``` cpp +wil::unique_semaphore s1; // failures throw +wil::unique_semaphore_nothrow s2; // failures return HRESULTs +wil::unique_semaphore_failfast s3; // failures terminate + +// Create during construction (not allowed with unique_semaphore_nothrow) +wil::unique_semaphore s4(0, 4, L"MySemaphoreName"); + +// Standard operations +s1.ReleaseSemaphore(); + +// Standard operations when going out of scope: +auto releaseOnExit = s1.ReleaseSemaphore_scope_exit(); + +// Acquire semaphore and release when going out of scope: +auto releaseOnExit = s1.acquire(); + +// Create or Open a Semaphore +s1.create(0, 2); +s1.open(L"MySemaphoreName"); +if (s1.try_create(0, 4, L"MySemaphoreName")) {} +if (s1.try_open(L"MySemaphoreName")) {} +``` + +When dealing with semaphore handles outside of `unique_semaphore`, WIL +defines some simple methods to emulate the same RAII patterns: + +``` cpp +// Release the semaphore when the returned value goes out of scope +auto releaseOnExit = wil::ReleaseSemaphore_scope_exit(handle); +```