https://kotlinlang.org logo
Title
a

Abhi

02/21/2022, 7:10 AM
internal interface ExclusiveObject {
    val mutex: Mutex
}

internal suspend inline fun <R> ExclusiveObject.lockByCoroutineJob(block: () -> R): R {
    return if(mutex.holdsLock(coroutineContext.job)) block()
    else mutex.withLock(coroutineContext.job) {
        block()
    }
}
Is this safe? Each Co-routine checks if the mutex is held by itself, identified by the co-routine job, if yes, it executes the block, else, it executes the block, with lock. what are the pitfalls? Will this scale when the pressure is high on acquiring the mutex?
a

Adam Powell

02/21/2022, 3:14 PM
a

Abhi

02/22/2022, 4:09 PM
Thanks, will look into it