Kotlin delay 是否在内部使用调度程序来解锁调用者线程?

Does Kotlin delay use a dispatcher internally to unblock the caller thread?

这是我用来学习 kotlin 协程的一些测试代码。该代码按预期工作,大约需要 1 秒来打印总和,但现在如果我用像网络请求这样的阻塞调用替换 delay(1000),那么代码大约需要 10 秒来打印总和(每次调用大约需要 1第二),但是如果我将网络调用包装在 withContext 中并使用 IO 调度程序,则需要 1 秒来打印总和,因为它是 运行 在不同的线程上。延迟函数是否使用某种调度程序来解锁线程?


suspend fun asyncDoubleFn(num: Int): Int {
    delay(1000)
    return num * 2
}


fun main() = runBlocking {
    launch {
        val tt = measureTimeMillis {
            val results = mutableListOf<Deferred<Int>>()
            for (num in 0..10) {
                val result = async { asyncDoubleFn(num + 1) }
                results.add(result)
            }
            val sum = results.map { it.await() }.reduce { acc, i -> acc + i }
            println("[SUM]: $sum")
        }

        println("[TT]: $tt")
    }


    launch {
        println("Another coroutine")
    }

    println("Main Code")


}

Does the delay function use some kind of a dispatcher to unblock the thread?

不只是 delay。所有可挂起的函数都与调度程序交互。

你应该问的问题是:"Which dispatcher is in charge here?"

答案是:runBlocking 安装它自己的调度程序,该调度程序调度到调用它的线程。您代码中的 launchasync 都继承了它。

考虑到这一点:

If I replace delay(1000) by a blocking call like a network request, then the code takes about 10 seconds to print the sum (each call takes around 1 second)

每个阻塞调用都将保留在调度程序的单个线程中。被阻止时将无法执行任何其他工作。

but if I wrap the network call in a withContext and use the IO dispatcher it takes 1 second to print the sum, because it is run on a different thread

是的,这改变了调度程序,问题解决了。

那么,delay 是做什么的呢?它暂停当前协程(async 启动的协程)和 returns 调度程序的控制,它现在可以继续你的循环并启动下一个协程。