withPermitOrNull

suspend fun <T> Semaphore.withPermitOrNull(timeout: Duration, block: suspend () -> T): T?

Runs block while holding a permit, waiting at most timeout for one, returning null on timeout.

A non-positive timeout degrades to a single Semaphore.tryAcquire attempt. Once a permit is acquired, block runs without any further deadline and the permit is released even when block throws.

Cancellation: waiting for a permit is cancellable and rethrows without consuming a permit; cancellation inside block releases the permit and rethrows.

Parameters

timeout

how long to wait for a permit.