Semaphore class

A semaphore object that allows a limited number of futures to acquire it.

A semaphore is a synchronization primitive that maintains a counter indicating the number of available resources or permits. In this implementation, the semaphore keeps track of an internal counter. The counter is decremented each time a future acquires the semaphore using the acquire method and incremented each time the semaphore is released using the release method.

When multiple futures are waiting for the semaphore, they will be put in a FIFO queue and only the first one will proceed when the semaphore becomes available.

The Semaphore class is inspired by the Python asyncio.Semaphore class.

Example usage:

final semaphore = Semaphore(2); // Create a semaphore with a limit of 2 permits

await semaphore.acquire(); // Acquire a permit
// Perform some asynchronous operation
semaphore.release(); // Release the permit

See also: Python documentation

Implementers

Constructors

Semaphore(int value)
Create a new Semaphore object with the initial internal counter set to value.

Properties

hashCode int
The hash code for this object.
no setterinherited
locked bool
Whether this semaphore cannot be acquired immediately.
no setterinherited
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
waiters int
Number of futures which are currently waiting to acquire this semaphore.
no setterinherited

Methods

acquire() Future<void>
Acquire the semaphore. If the internal counter is greater then 0, decrease it by 1 and return immediately. If the internal counter equals 0, wait asynchronously until the semaphore is available.
inherited
cancelAll() → void
Cancel all futures waiting for this semaphore to be available by throwing a SemaphoreAcquireFailureException to them.
inherited
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
release() → void
Increase the internal counter by 1 and may wake up a future waiting to acquire this semaphore.
inherited
run<T>(Future<T> func()) Future<T>
Acquire the semaphore, asynchronously run func and release the semaphore afterwards.
inherited
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited