`yield()` to run pending coroutines does not seem ...
# coroutines
p
yield()
to run pending coroutines does not seem to work on Kotlin Playground, wonder why is that
j
Note that yield is not guaranteed to actually do that, depending on the dispatcher
p
@jw I noticed from docs, but still even when using Dispatchers.Default I don’t see it working, I’m not even sure it’s suspending at all
Same code on local JVM seems to consistently print “coroutine started”
j
It probably runs in a container/cgroup that only has access to a single virtual CPU core
So the number of threads is different and that causes different behavior
Usually it's cores+1 though
d
Dispatchers.Default
is a multi-threaded dispatcher, so
yield
just means "relinquish the thread." However, the coroutine
launch
-ed is likely going to use a different thread. So, what happens here is a race: if, after the
yield
, the
cancel
manages to finish before the coroutine actually starts, the coroutine will not be run. So, there are no guarantees one way or another for whether
yield
helps here.
p
Makes sense. Using
newSingleThreadContext(“single thread”)
on playground eliminates the race it seems
d
In this example, the
withContext
coroutine does not relinquish its thread at all, but with enough time, another thread is provisioned.
p
Yeah, mystery solved. @Dmitry Khalanskiy [JB] I think it’s fair to say that when using a single threaded dispatcher,
yield
will always run the pending coroutine with no risk of races ?
d
In practice, yes. In theory, you can implement a dispatcher any way you want, including randomly choosing which task to run next.
p
Gotcha. Thanks y’all!