Semaphore

interface Semaphore

A counting semaphore for coroutines that logically maintains a number of available permits. Each acquire takes a single permit or suspends until it is available. Each release adds a permit, potentially releasing a suspended acquirer. Semaphore is fair and maintains a FIFO order of acquirers.

Semaphores are mostly used to limit the number of coroutines that have an access to particular resource. Semaphore with permits = 1 is essentially a Mutex.

Functions

acquire
Link copied to clipboard
common
abstract suspend fun acquire()
Acquires a permit from this semaphore, suspending until one is available.
release
Link copied to clipboard
common
abstract fun release()
Releases a permit, returning it into this semaphore.
tryAcquire
Link copied to clipboard
common
abstract fun tryAcquire(): Boolean
Tries to acquire a permit from this semaphore without suspension.

Properties

availablePermits
Link copied to clipboard
common
abstract val availablePermits: Int
Returns the current number of permits available in this semaphore.

Extensions

withPermit
Link copied to clipboard
common
inline suspend fun <T> Semaphore.withPermit(action: () -> T): T
Executes the given action, acquiring a permit from this semaphore at the beginning and releasing it after the action is completed.

Sources

common source
Link copied to clipboard