Testing the new `limitedParallelism` slicing I am ...
# coroutines
g
Testing the new
limitedParallelism
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 😄
Copy code
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")
      }
    }
  }
j
limitedParallelism
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.
If you want to prevent concurrency for some pieces of code, then
Mutex
is a correct way to go
g
@Joffrey Thank you so much for the explanation, I suppose when the first coroutine suspends the thread becomes available to run the second coroutine. Was just reading this comment and it is totally in sync with yours. Cheers!
👍 1
j
I suppose when the first coroutine suspends the thread becomes available to run the second coroutine
This is exactly what happens