Search code examples
kotlinkotlin-coroutinescoroutinesuspend

Kotlin Coroutines: on which thread the suspend function runs on?


I am new to Kotlin Coroutines and I have a question that I am not able to find a direct answer anywhere. The question is simple: if I have a coroutine and I call a suspend function (which could potentially call another one), from my understanding, the coroutine is suspended and the suspend function does not know about the coroutine anymore; then, within the suspend function, on what thread it runs if it still needs to process something (outside of another inner suspend function)?

Here are my experimental codes:

import kotlinx.coroutines.*

fun main(): Unit = runBlocking {
    println("parent ${Thread.currentThread().name}")
    test()

    launch (Dispatchers.IO) {
        println("parent2 ${Thread.currentThread().name}")
        test2()
    }
}

suspend fun test() {
    delay(1)
    println("child ${Thread.currentThread().name}") //Who processes this?
}

suspend fun test2() {
    delay(1)
    println("child2 ${Thread.currentThread().name}") //Who processes this?
}

It seems the within the suspend function, it is running on the same thread as the calling coroutine's. But I am not sure.


Solution

  • It runs on the same thread that called it, up to the first suspension point (call to another suspend function that suspends), assuming it calls a suspend function. Then when it resumes from suspension, it runs on whatever thread is assigned by the current CoroutineContext’s dispatcher. It’s up to the dispatcher to determine the logic of using/reusing threads from its own pool.

    Note that runBlocking’s CoroutineContext comes with its own single-threaded dispatcher that uses the thread it was called from.