Semaphore class
A counting semaphore for tasks.
- Use
import ThinkMeta.ConcurrentTasks.Synchronization.Semaphore;- Namespace
ThinkMeta::ConcurrentTasks::Synchronization- Inherits
Suspendable
Syntax
using Semaphore = _Semaphore<SuspensionKind::Multiple>;
using Semaphore_s = _Semaphore<SuspensionKind::Single>;Template parameters
_SuspensionKindSuspensionKindSuspensionKind::Multiple: any number of waiting tasks;SuspensionKind::Single: at most one waiting task at a time, cheaper, with timeouts.
Remarks
Wait takes one permit, suspending the calling task while the count is 0; Release adds permits and resumes as many waiters as it can serve. Comes as Semaphore (any number of waiters) and Semaphore_s (one waiter). Wait suspends and needs a task or an OS thread converted with ConvertThreadToTask. Release and TryWait never suspend and may be called from any thread; any task may release, not only one that waited. The count has no upper limit; keep it within the range of std::size_t. No member reports errors. Destroy the semaphore only when no task can wait on it or release it any more and the last Release has returned; the return of a Wait alone does not mean that (both variants).
See also
SemaphoreLock, SpinSemaphoreLock
Names
| Name | Description |
|---|---|
Semaphore |
Counting semaphore for any number of waiting tasks (no timeouts). |
Semaphore_s |
Counting semaphore for at most one waiting task at a time.
Cheaper than |
Constructors
Semaphore
Creates the semaphore with initial permits.
Syntax
explicit Semaphore(std::size_t initialCount) noexcept;Parameters
initialCountstd::size_t- The number of permits available at once.
Methods
Release
Adds permits and resumes waiting tasks while permits last.
Syntax
void Release(std::size_t count = 1) noexcept;Parameters
countstd::size_t- The number of permits to add.Default:
1
Remarks
Never suspends; any thread.
See also
Wait
Takes one permit, waiting for it if necessary.
Syntax
void Wait() noexcept;Remarks
Suspends the calling task until a Release hands it a permit. Task or converted thread only; Semaphore_s: at most one waiter at a time.
See also
_s only
Takes one permit, waiting for it with a time limit.
Syntax
[[nodiscard]] bool Wait(Duration timeout) noexcept;Parameters
timeoutDuration- The longest time to wait. Needs
EnableTimers; without it the wait has no limit.
Return value
Type: bool
true if a permit was taken; false if it timed out, no permit was taken then.
Remarks
Semaphore_s only. Task or converted thread only.
See also
TryWait
Takes one permit if one is available.
Syntax
[[nodiscard]] bool TryWait() noexcept;Return value
Type: bool
true if a permit was taken; false if the count was 0.
Remarks
Never suspends; any thread.
See also
Generated from ThinkMeta.ConcurrentTasks.API @ 137ec1d (2026-10-17).