Is there something like a Mutex for suspend functions that works in JS and in JVM? I need to prevent that a suspend function is executed concurrently by multiple callers. I tried synchronized
but that does not work.
Here is some JVM code to illustrate my problem. It is not even working in JVM (IllegalMonitorStateException) but I think it makes it clear what I want to do:
class Test {
var value: Int = 0
suspend fun asyncFunc() = synchronized(this) {
value++
val result = value
delay(100)
assertTrue { value == result } // fails if asyncFunc is executed concurrently
}
@Test
fun testMethod() = runBlocking {
val job0 = async {
asyncFunc() // mutates value
}
delay(10)
async {
asyncFunc() // mutates value concurrently (what I want to prevent)
}.await()
job0.await()
}
}
What missing is IMHO something like:
suspend fun <R> synchronizedSuspend(lock: Any, block: () -> R): R