Another question. Why `Mutex` is not reentrant? I'...
# coroutines
l
Another question. Why
Mutex
is not reentrant? I'd love to have it for transactional stuff ("reliable writes" in BluetoothGatt). Is there an alternative? FYI, here's how I want to use it: https://gist.github.com/LouisCAD/88d06da6ae1caf04acbf6cd4fc1d5cac#file-gattconnection-kt-L56 EDIT: Added line of the relevant method in the link
e
The concept of reentrant mutex does not combine well with the concept of coroutines. Coroutines, unlike threads, are not just light-weight. They are ephemeral. Any task that is done inside one coroutine can be decomposed into multiple sub-coroutines at any moment of time. How would “reentrant mutex” know whether you are trying to acquire it “again” as part of “the same” job, or this is another job and it shall wait. There is no conceptual way to tell. That is also why there is no out-of-the-box support for mutable “coroutine-local” variables. They don’t make sense in coroutines world just like reentrant mutexes.
Just use actors instead of mutexes.
l
I didn't used actors yet, but I have read about them in the guide, and I don't see how they would help me in this case. The mutex is important to ensure the operation has been completed (i.e. the appropriate callback has been fired) before starting another one. The "reliable write" needs to wrap
writeCharacteristic(...)
calls (including their callback), and no other things than writes must be done until the writes are commited. I'm thinking about adding a
reliableWriteOngoing
boolean flag to let
writeCharacteristic(...)
bypass the already locked mutex, I guess it should work correctly. Do you think I could do better with actors?
So I ended up using the boolean flag I was talking about plus a second mutex used fro writes when this flag is true. My gist has been updated if you're interested in the implementation