Question about the <limitedParallelism> API. Is th...
# coroutines
r
Question about the limitedParallelism API. Is the following assumption correct?
Copy code
val singleDispatcher = Dispatchers.IO.limitedParallism(1)

suspend fun codeBlockA() = withContext(singleDispatcher) { .. }

suspend fun codeBlockB() = withContext(singleDispatcher) { .. }
Never in time will code inside functions
codeBlockA
and
codeBlockB
be running at the same time. Irrespective of when / how often they are invoked and/or what parent coroutine there are launched from. Correct?
👌 1
so if
codeBlockB
is invoked while
codeBlockA
is still executing, the
singleDispatcher
will then 'queue' the coroutine until
singleDispatcher
is 'free' for execution? Similar to thread confinement?
👌 1
With the difference that the 'next' coroutine could be executed on a different thread. But only when the previous one is finished?
👌 1
j
That's how I understood it as well, yes
r
thnx
@Joffrey to follow up, what if there is a dispatcher switch inside one of the blocks? e.g.
Copy code
val singleDispatcher = Dispatchers.IO.limitedParallism(1)

fun myFunction() {
  scope.lauch(singleDispatcher) {
    val a = someOtherFunction() = withContext(<http://Dispatcher.IO|Dispatcher.IO>) { ... }

  }
}
what happens then? does this code still guarantees that it's run on singleDispatcher?
j
Not 100% sure, but I believe the way it should behave is that the stuff running inside the
withContext(<http://Dispatchers.IO|Dispatchers.IO>)
would not be subject to the parallelism limit
r
so I should also dispatch that code with
singleDispatcher
to prevent concurrency?
Maybe @louiscad knows, the coroutine guru? 😄
l
The code running in the dispatcher might suspend, and then, you still have concurrency that you need to take into account. The blocking portions will never execute concurrently though. If you need to prevent concurrency across coroutines (and across suspension points),
Mutex
is the API you're looking for.
r
so calling a second suspending function inside a
myFunction()
and also preventing concurrency is not possible with .limitedParallism API?
even when I dispatch that code onto the same
singleDispatcher
?
l
limitedParallelism is only an alternative to single threaded dispatchers. It's not a replacement for Mutexes.
✔️ 1