StmSemaphore

STM-based semaphore for concurrency limiting using transactional memory.

Unlike mutex-based semaphores, STM semaphores can be composed with other transactional operations atomically.

Basic usage:

val sem = StmSemaphore.create(5)
val acquired = atomically { with(sem) { acquire() } } // true
println(sem.availablePermits()) // 4
atomically { with(sem) { release() } }
println(sem.availablePermits()) // 5

Composing with state machine:

val sem = StmSemaphore.create(3)
val sm = StmStateMachine.create(State.IDLE)

atomically {
val acquired = with(sem) { acquire() }
if (acquired) {
with(sm) { transition(State.RUNNING) }
}
}

Types

Link copied to clipboard
object Companion

Factory for StmSemaphore.

Functions

Link copied to clipboard
fun STM.acquire(): Boolean

Attempts to acquire a permit within an STM transaction. Returns true if a permit was acquired, false if none are available.

Link copied to clipboard
fun STM.available(): Int

Reads the number of available permits within an STM transaction.

Link copied to clipboard
suspend fun availablePermits(): Int

Reads the number of available permits by running an atomic transaction.

Link copied to clipboard
fun STM.release()

Releases a permit within an STM transaction. Will not exceed maxPermits.