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

elaborate tissue

11/11/2019, 2:47 AM
withContext(Dispatchers.IO) { }, would you guys say this is similar to the coroutine saying "hey i'm about to perform some slow task, does anyone else speedier want to jump in before me?"
o

octylFractal

11/11/2019, 2:50 AM
no, this is saying "I'm about to perform some blocking work, switching to a larger thread pool to avoid stopping other tasks"
e

elaborate tissue

11/11/2019, 2:59 AM
so how does the underlying OS decide which thread from which pool to run, it's just first come first serve correct? so an example: if i had a cpu with 8 cores, and i had 8 coroutines running (that were yieldling occasionally) on Dispatchers.Default, and I submit some coroutines to Dispatchers.IO, do those get run fairly so on the next yield from Dispatchers.Default a Dispatchers.IO coroutine runs?
i guess i dont really get the benefit of switching into Dispatchers.IO, its just got a bigger threadpool... is it that by Dispatchers.Default having a limited-to-cpu thread pool it can optimize?
o

octylFractal

11/11/2019, 3:01 AM
I think you misunderstand how coroutines work -- the OS doesn't get involved beyond threads. A standard OS scheduler will run threads according to their priority (which I believe both Default/IO use the same priority), not in a queue-like fashion. Your IO coroutines will likely run concurrently with your other coroutines, regardless of if you yield in your code.
The need for a bigger thread pool comes from blocking work -- when a coroutine blocks instead of suspending, it is not removed from the thread pool, so if you had, say, 8 network connections, and they were all blocking on
Default
, no work could be done. if they are blocking on
IO
, there are still many IO thread slots open, and all the
Default
thread slots are open.
👍 2
e

elaborate tissue

11/11/2019, 3:06 AM
cool, thanks that helps a lot
3 Views