Package kotlinx.coroutines.sync

Synchronization primitives (mutex).

Types

Mutex

interface Mutex

Mutual exclusion for coroutines.

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.

Functions

Mutex

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

fun Semaphore(
    permits: Int,
    acquiredPermits: Int = 0
): Semaphore

Creates new Semaphore instance.

withLock

suspend fun <T> Mutex.withLock(
    owner: Any? = null,
    action: () -> T
): T

Executes the given action under this mutex’s lock.

withPermit

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.