Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutex the right way

What is the right way to "synchronize" function which mutates shared state using Mutex? Using Mutex within a coroutine started with launch() or async() works as expected, but if I start a coroutine with runBlocking() the thread looks like blocked (locked) for a very long time. The thing is that the function might be called from multiple threads and I cannot solve this with thread confinement. What's the right way to use Mutex in this scenario?

like image 730
user221256 Avatar asked Nov 21 '25 04:11

user221256


1 Answers

The right way is to design your software in so that avoids usage of Mutex and other forms of shared mutable state altogether. If you have some resource or data structure that needs to be shared you can always encapsulate this data structure inside a separate coroutine and communicate with this coroutine when you need to do anything with this data structure. This design pattern is known as an actor. An actor is a pair of a coroutine and a channel it reads incoming messages from.

The advantage of this approach is that you can communicate asynchronously with an actor. If you send a message to an actor and don't wait for a response, then you can continue the work without having to wait for an actor to finish processing your message.

You can read a bit more about actors in the guide to kotlinx.coroutines.

like image 90
Roman Elizarov Avatar answered Nov 23 '25 09:11

Roman Elizarov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!