is there a way to wait for a mutex to unlock ? I h...
# coroutines
j
is there a way to wait for a mutex to unlock ? I have a method which fetches data and acquires the lock, while there is a read method which consumes the fetched data and returns some values. I dont want to acquire the lock everytime someone tries to fetch the data, only want to acquire the lock while writing the data.
d
is there a way to wait for a mutex to unlock ?
Nope, this operation would be completely meaningless.
Copy code
if (mutex.isUnlocked) {
  doSomething()
}
is susceptible to this issue: • Thread A checks
mutex.isUnlocked
. It receives
true
. • Thread B locks the mutex. • Thread B enters the section protected by the mutex and starts mutating the data. • Thread A calls
doSomething
.
thank you color 1
j
Makes sense, thank you for the explanation.
k
You want a read write lock, which coroutines doesn't currently support out of the box. https://github.com/Kotlin/kotlinx.coroutines/issues/94
☝🏻 1
d
Or even better, you could attempt to refactor the program to make data dependencies explicit. It's not always possible, but has the added benefit of improved readability/predictability and is often worth pursuing. For example,
MutableStateFlow
can represent some state changes to which should notify several consumers (and accessing
.value
doesn't need to be wrapped in a lock!). This is often a good solution to the problem of having multiple consumers.
👍 1
j
I was thinking using
MutableSharedFlow
instead, where I could use
.first()
which would be suspended until
the
write method emits the value, and the subsequent calls to the get method can get the values without the need to acquire the lock
d
Yep, that's possible if you set the
replay
parameter to
1
.