https://kotlinlang.org logo
#coroutines
Title
# coroutines
s

Seri

05/12/2020, 8:01 PM
Is there a way to synchronously check if a Mutex is unlocked and run a block of code under it? Similar to
Mutex.withLock { ... }
, but with calls while the Mutex is locked being discarded instead of suspending.
o

octylFractal

05/12/2020, 8:13 PM
is
tryLock
not good enough?
if you really want a `tryWithLock`:
Copy code
inline fun <T : Any> Mutex.tryWithLock(owner: Any? = null, action: () -> T): T? {
    return if (tryLock(owner)) {
        try {
            action()
        } finally {
            unlock(owner)
        }
    } else {
        null
    }
}
explicitly forbids
null
because it's the failure signal here, you can change that up if you want
s

Seri

05/12/2020, 8:21 PM
My issue with tryLock was that it didn’t immediately run the block, so there was a race condition.
That tryWithLock extension method is what I was thinking about writing, nice!
o

octylFractal

05/12/2020, 8:21 PM
I don't get what the race condition is here? if
tryLock
returns
true
, you got the exclusive lock -- nothing can interrupt it
s

Seri

05/12/2020, 8:23 PM
I think I had the synchronous bits mixed up in my head, I was imagining the following at first:
Copy code
if (!mutex.isLocked) {
    mutex.withLock { ... }
}
Looking back at that, I can see the flaw
o

octylFractal

05/12/2020, 8:24 PM
yea, there's a race condition there -- but I think
tryLock
should work
s

Seri

05/12/2020, 8:24 PM
👍
3 Views