How would I implement an "offensive" `Mutex`, aka ...
# coroutines
r
How would I implement an "offensive"
Mutex
, aka a
Mutex
where the coroutine holding the lock is killed instead of waited for?
c
Killed… when? It holds the lock and is presumably doing the work, just exit/cancel the coroutine?
a
d
I've very interested in what possible use-case you would have.
p
If i correctly understand (jvm code example cause of atomic reference):
Copy code
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")
        }
    }
}
nod 1