From be068916d46589dc115688238510c235d1c746f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C3=A9ter=20Kardos?= Date: Mon, 11 Mar 2024 18:47:37 +0100 Subject: [PATCH] semaphore docs --- README.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/README.md b/README.md index bf3671d..6864b99 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ - [broadcast_event](#feature_event) - [mutex](#feature_mutex) - [shared_mutex](#feature_mutex) +- [semaphores](#feature_semaphore) **Utilities**: - [join](#feature_join) @@ -350,6 +351,31 @@ task lock_shared_mutex(shared_mutex& mtx) { } ``` +### Semaphores + +Semaphores are also very similar to their standard library counterparts. There is a `counting_semaphore` variant, where you can specify the maximum value of the semaphore's counter, and there is a `binary_semaphore` variant that specifies the maximum value to one. + +Usage of semaphores is similar to the standard library equivalent, but you need to use ˙co_await` to acquire the semaphore: + +```c++ +counting_semaphore sema(0, 16); // Counter may go up to 16, current value at 0. + +// A coroutine +launch([](counting_semaphore& sema){ + co_await sema; + std::cout << "This runs second." << std::endl; +}(sema)); + +// Another coroutine +launch([](counting_semaphore& sema){ + std::cout << "This runs first." << std::endl; + sema.release(); +}(sema)); +``` + +Unlike the standard library semaphore, semaphores in `asyncpp` don't have an implementation defined upper limit for the counter so you can go up to `std::numeric_limits::max()`. In `asyncpp`, semaphores will also complain (via `std::terminate`) if you exceed the maximum value of the counter by releasing too many times. + + ### Join To retrieve the result of a coroutine, we must `co_await` it, however, only a coroutine can `co_await` another one. Then how is it possible to wait for a coroutine's completion from a plain old function? For this purpose, `asnyncpp` provides `join`: