interface Mutex(source)

Mutual exclusion for coroutines.

Mutex has two states: locked and unlocked. It is non-reentrant, that is invoking lock even from the same thread/coroutine that currently holds the lock still suspends the invoker.

JVM API note: Memory semantic of the Mutex is similar to synchronized block on JVM: An unlock operation on a Mutex happens-before every subsequent successful lock on that Mutex. Unsuccessful call to tryLock do not have any memory effects.


Link copied to clipboard
abstract val isLocked: Boolean

Returns true if this mutex is locked.

Link copied to clipboard
abstract val onLock: SelectClause2<Any?, Mutex>

Clause for select expression of lock suspending function that selects when the mutex is locked. Additional parameter for the clause in the owner (see lock) and when the clause is selected the reference to this mutex is passed into the corresponding block.


Link copied to clipboard
abstract fun holdsLock(owner: Any): Boolean

Checks whether this mutex is locked by the specified owner.

Link copied to clipboard
abstract suspend fun lock(owner: Any? = null)

Locks this mutex, suspending caller until the lock is acquired (in other words, while the lock is held elsewhere).

Link copied to clipboard
abstract fun tryLock(owner: Any? = null): Boolean

Tries to lock this mutex, returning false if this mutex is already locked.

Link copied to clipboard
abstract fun unlock(owner: Any? = null)

Unlocks this mutex. Throws IllegalStateException if invoked on a mutex that is not locked or was locked with a different owner token (by identity).

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.