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

dave08

12/27/2018, 1:04 PM
If I have
class Foo { suspend fun execute(): Bar }
and I want to limit that
execute
should not run in parallel is the simplest way (without channels) to use
newSingleThreadContext
to create one thread context in the class and use it in
withContext(executeContext)
in
execute
? Is there anything wrong with this, or a better way?
d

Dominaezzz

12/27/2018, 1:11 PM
I don't know if this is better but for something like that I'd use a
Mutex
. https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.sync/-mutex/
d

dave08

12/27/2018, 1:13 PM
I need it to run off the main thread anyways, so the context switching is inevitable, but I use Mutex for another similar case that doesn't require context switching.
d

Dominaezzz

12/27/2018, 1:17 PM
So you're not using an existing dispatcher then?
d

dave08

12/27/2018, 1:19 PM
The existing dispatchers are pools, so if a thread is free, it will run the next
execute
in parallel AFAIK, which is not what I want. By limiting to one thread, it'll block until I return the first result. I could call this from many threads and it should still be FIFO.
d

Dominaezzz

12/27/2018, 1:23 PM
By limiting to one thread you do get implicit synchronization. I was thinking you could still re-use the existing dispatchers' threads, if you use explicit synchronization(
Mutex
).
d

dave08

12/27/2018, 1:23 PM
Any advantage to that?
d

Dominaezzz

12/27/2018, 1:23 PM
You don't create another thread?
If your function is possibly called from an existing dispatcher, there might be no thread switching.
d

dave08

12/27/2018, 1:24 PM
It's just a temporary one, the question is how much overhead will that involve compared to
Mutex
?
there might be no thread switching
Mutex
is less overhead than that switching I'm saving?
d

Dominaezzz

12/27/2018, 1:27 PM
I reckon it is less overhead but I don't know.
d

dave08

12/27/2018, 1:28 PM
I guess it's worth a try, thanks 🙂.
6 Views