Search code examples
kotlincoroutinesuspend

Kotlin coroutine suspend continuation thread


I'm trying to understand how coroutines work under the hood. I have this simple code that suspends the coroutine and resumes it in a different thread.

fun main(){
    fun pt(msg : String){
        println("${Thread.currentThread().name}: ${msg}")
    }
    suspend fun a(){
        pt("A")
        suspendCoroutine { cont ->
            thread (name = "new thread") {
                pt("resuming")
                cont.resume(Unit)
            }
        }
        pt("B")
    }
    runBlocking {
        a()
    }
}

Since the coroutine is resumed in new thread I was expecting that the printing of B is also done by this thread, but it doesn't seem to be the case.

main: A
new thread: resuming
main: B

Can anybody explain what's going on? Is the original thread that started the coroutine part of the continuation object and the resume call passes the execution to it?


Solution

  • You are not resuming in a new thread. You are using the new thread to do something (printing “resuming”) while the coroutine is suspended and to instruct the coroutine to then resume. This thread is then done with. This is not how you would get a thread to do coroutine work. Dispatchers are responsible for assigning blocks of coroutine work to threads.