Actually, I figured out I made a mistake, but it led to a confusing result.
suspend inline fun <T> Mutex.test(wait: Boolean, action: () -> T): T? {
return if (tryLock()) {
try {
action()
} finally {
unlock()
}
} else {
if (wait) withLock(action = action) else null
}
}
suspend fun Mutex.demo(message: String, delay: Long = 3000L, wait: Boolean = false) {
if (
test(wait) {
println("start: $message")
Thread.sleep(delay)
println("end: $message")
} == null
) {
println("skip: $message")
}
}
fun main(args: Array<String>) = runBlocking<Unit> {
val lock = Mutex()
launch { lock.demo("A", wait = false) }
delay(50)
launch { lock.demo("B", wait = false) }
delay(50)
launch { lock.demo("C", wait = false) }
}
Notice the
Thread.sleep()
in
demo()
. If I replace it with a
delay()
it works as expected, but with
Thread.sleep()
, they all wait. Is that expected?