Guilherme Almeida
01/10/2022, 11:50 AMlimitedParallelism
slicing I am not sure I fully understand how it works. Looking at the example below I am launching Access #1
and a second later Access #2
.
Using the accessDispatcher
with limited parallelism of 1 I would think the Access #2
could only start after the Access #1
was finished. So I expected the prints to go 1,2,3 but they go 1,3,2 instead. Could anyone point out why this is the actual behaviour? I know this can be solved with something like a Mutex, but I am trying to understand the behaviour of these new sliced dispatchers 😄
private val mainScope = MainScope()
private val accessDispatcher = Dispatchers.IO.limitedParallelism(1)
public fun foo() {
mainScope.launch {
mainScope.launch(accessDispatcher + CoroutineName("Access #1")) {
println("Step 1")
delay(5.seconds)
println("Step 2")
}
delay(1.seconds)
mainScope.launch(accessDispatcher + CoroutineName("Access #2")) {
println("Step 3")
}
}
}
Joffrey
01/10/2022, 11:52 AMlimitedParallelism
limits.. well... parallelism. It doesn't limit concurrency.
What limitedParallelism(1)
means is that you won't have 2 coroutines running code at the same time in 2 different threads. However, your coroutines can still interlace (they are still concurrent).
Also, note that different pieces of your coroutines can be run by different threads, just not at the same time.Joffrey
01/10/2022, 11:54 AMMutex
is a correct way to goGuilherme Almeida
01/10/2022, 12:01 PMJoffrey
01/10/2022, 12:03 PMI suppose when the first coroutine suspends the thread becomes available to run the second coroutineThis is exactly what happens