Hi, just starting to learn Mutex in Kotlin. I have...
# coroutines
j
Hi, just starting to learn Mutex in Kotlin. I have a situation where I have multiple instances of a class that will work on multiple threads. And the work is a heavy computation work that takes more than 10 seconds. I want the threads to add items to the same SynchronizedList using Mutex. The work, i.e. compute() method will be a suspendable function working as a coroutine. Should I create a single, shared Mutex instance for all instances that do the heavy work? I found an example for a single instance doing work using coroutines and the Default Dispatcher, but I am not so sure about multiple instances. Any help would be appreciated.
s
Generally speaking there are better ways than creating your own mutex. The choice will depend on how you need to use the resulting list. The typical pattern is to use
async
to start each worker coroutine and put the deferred results into a list, then use
awaitAll
. Or if you need more flexibility, e.g. to access some results while others are still being computed, you could have the worker coroutines send their results to a shared channel, and then launch one additional coroutine to collect the results.
k
If that
SynchronizedList
is really acting as a queue of work, you should instead look into
Channel
.