kotlincoroutine

What is the purpose of coroutine yield()?


I'm not exactly sure what is the purpose of the yield function. Can you check this example I have?

I am following an example here.

Here is the code:

val job = launch {
    val child = launch {
        try {
            delay(Long.MAX_VALUE)
        } finally {
            println("Child is cancelled")
        }
    }
    yield() //why do i need this ???????
    println("Cancelling child")
    child.cancel()
    child.join()
    yield()
    println("Parent is not cancelled")
}
job.join()

When I comment out the first yield I get the following results:

but if I leave the yield as it is I get:

What does it mean to use yield here?


Solution

  • https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/yield.html

    Yields a thread (or thread pool) of the current coroutine dispatcher to other coroutines to run. If the coroutine dispatcher does not have its own thread pool (like Dispatchers.Unconfined) then this function does nothing, but checks if the coroutine Job was completed. This suspending function is cancellable. If the Job of the current coroutine is cancelled or completed when this suspending function is invoked or while this function is waiting for dispatching, it resumes with CancellationException.

    It accomplishes at least a few things

    1. It temporarily deprioritises the current long running CPU task, giving other tasks a fair opportunity to run.
    2. Checks whether the current job is cancelled, since otherwise in a tight CPU bound loop, the job may not check until the end.
    3. Allows for progress of child jobs, where there is contention because more jobs than threads. This may be important where the current job should adapt based on progress of other jobs.