reactormonk
08/21/2024, 4:47 PMMutex
, aka a Mutex
where the coroutine holding the lock is killed instead of waited for?Chris Lee
08/21/2024, 5:29 PMAlex Vanyo
08/21/2024, 5:33 PMMutatorMutex
that’s implemented in Compose:
https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/[…]torMutex.kt;l=78;drc=64c19e2612ecaca5c53a3f7b96d7b4fec2991709Daniel Pitts
08/21/2024, 7:05 PMPHondogo
08/21/2024, 7:05 PMclass OffensiveMutex {
private val currentJob = AtomicReference<Job?>()
suspend fun <T> withLock(lambda: suspend () -> T): T {
return coroutineScope {
val job = currentCoroutineContext().job
val prevJob = currentJob.getAndSet(job)
try {
prevJob?.cancelAndJoin()
lambda()
} finally {
currentJob.compareAndSet(job, null)
}
}
}
}
suspend fun main() {
coroutineScope {
val mutex = OffensiveMutex()
repeat(10) {
launch {
mutex.withLock {
try {
delay(100)
println("finish $it")
} catch (e: CancellationException) {
println("cancel $it")
throw e
}
}
}
delay(1)
}
mutex.withLock {
println("finish final")
}
}
}