reactormonk
Mutex
Chris Lee
Alex Vanyo
MutatorMutex
Daniel Pitts
PHondogo
class 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") } } }
A modern programming language that makes developers happier.