Package kotlinx.coroutines.sync

Synchronization primitives (mutex).

Types

Mutex
Link copied to clipboard
interface Mutex

Mutual exclusion for coroutines.

Semaphore
Link copied to clipboard
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.

Functions

Mutex
Link copied to clipboard
fun Mutex(locked: Boolean = false): Mutex

Creates a Mutex instance. The mutex created is fair: lock is granted in first come, first served order.

Semaphore
Link copied to clipboard
fun Semaphore(permits: Int, acquiredPermits: Int = 0): Semaphore

Creates new Semaphore instance.

withLock
Link copied to clipboard
inline suspend fun <T> Mutex.withLock(owner: Any? = null, action: () -> T): T

Executes the given action under this mutex's lock.

withPermit
Link copied to clipboard
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.