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

christophsturm

12/30/2020, 4:27 PM
if I use launch {} with a multithreaded coroutines dispatcher, will the whole launch block run in the same thread, or will the thread change possibly after return from a suspend method?
a

Adam Powell

12/30/2020, 4:30 PM
The thread can change when a suspended coroutine resumes
a

andylamax

12/30/2020, 4:44 PM
Experience has shown me this. If you only have one suspend function running at that particular time, despite having a multithreaded dispather your coroutine will run in one thread. This is not the case if at the particular moment, there are other concurrent coroutines running. Thus when it suspends, it tends to resume on a free thread. A free thread in this context is thread that either hasn't run any coroutine yet, or has suspended and is waiting for a coroutine to resume
z

Zach Klippenstein (he/him) [MOD]

12/31/2020, 2:07 AM
I think that’s an implementation detail of the current default dispatcher. It’s not part of the dispatcher contract, and something which could potentially change at any time, so it’s not safe to rely on that behavior. Why do you care what thread continuations are invoked on? Despite the fact that the thread might change, the code in a single coroutine will always be run sequentially. If you have a use case that requires all the code to execute on a specific thread, it would probably be best to create a dedicated dispatcher that explicitly knows about that thread and only executes continuations on it. Eg what
Dispatchers.Main
does.
4
c

christophsturm

12/31/2020, 10:02 AM
My code is a multi threaded Test Runner and I want to measure Test duration with getCurrentThreadCpuTime
And I wanted to understand why It gave strange numbers sometimes
4 Views