Open dkhalanskyjb opened 1 month ago
Coroutines themselves don't know whether they were started in an undispatched manner, and so yield
can not disable the optimization in these special cases. We can teach coroutines that, but this requires that we modify our JobSupport
state machine significantly. A less nice solution is to just remove the optimization.
Describe the bug
yield()
introduces special behavior for optimization: instead of callingdispatch
, it calls a specializeddispatchYield
function. In theory, that function allows for some optimization: we know we're already executing a coroutine on the correct thread, so we can skipyield
altogether if there are no other coroutines scheduled; we know the coroutine is going to suspend immediately, so we don't need to spawn a new worker to accommodate it; and so on.This theory breaks because of
CoroutineStart.UNDISPATCH
: if we callyield()
the first thing in an undispatched coroutine, none of this is true.Provide a Reproducer
Currently, because this optimization is very selectively applied, only
Dispatchers.Default
suffers from this, and because of an internal check, only when the new coroutine is started from a kotlinx-coroutines-controlled thread.Prints
The new thread that was supposed to be used for the new coroutine after it's yielded does not actually wake up, causing an unjustified delay.