lock

abstract suspend fun lock(owner: Any? = null)(source)

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

This suspending function is cancellable: if the Job of the current coroutine is cancelled while this suspending function is waiting, this function immediately resumes with CancellationException. There is a prompt cancellation guarantee: even if this function is ready to return the result, but was cancelled while suspended, CancellationException will be thrown. See suspendCancellableCoroutine for low-level details. This function releases the lock if it was already acquired by this function before the CancellationException was thrown.

Note that this function does not check for cancellation when it is not suspended. Use yield or CoroutineScope.isActive to periodically check for cancellation in tight loops if needed.

Use tryLock to try acquiring the lock without waiting.

This function is fair; suspended callers are resumed in first-in-first-out order.

It is recommended to use withLock for safety reasons, so that the acquired lock is always released at the end of the critical section, and unlock is never invoked before a successful lock acquisition.

Parameters

owner

Optional owner token for debugging. When owner is specified (non-null value) and this mutex is already locked with the same token (same identity), this function throws IllegalStateException.