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

Remy Benza

06/28/2022, 5:11 PM
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

Joffrey

06/28/2022, 5:38 PM
That's how I understood it as well, yes
r

Remy Benza

06/29/2022, 7:51 AM
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

Joffrey

07/10/2022, 6:05 PM
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

Remy Benza

07/10/2022, 6:25 PM
so I should also dispatch that code with
singleDispatcher
to prevent concurrency?
Maybe @louiscad knows, the coroutine guru? 😄
l

louiscad

07/10/2022, 6:30 PM
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

Remy Benza

07/10/2022, 6:40 PM
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

louiscad

07/10/2022, 7:02 PM
limitedParallelism is only an alternative to single threaded dispatchers. It's not a replacement for Mutexes.
✔️ 1
3 Views