gpt4 book ai didi

kotlin - Kotlin延迟是否在内部使用调度程序来取消阻塞调用者线程?

转载 作者:行者123 更新时间:2023-12-02 13:36:34 25 4
gpt4 key购买 nike

这是我用来学习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。所有可挂起的函数都与调度程序交互。

您应该问的问题是:“这是哪个调度员负责?”

答案是: 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启动的协程),并将控制权返回给调度程序,调度程序现在可以继续以恢复循环并启动下一个协程。

关于kotlin - Kotlin延迟是否在内部使用调度程序来取消阻塞调用者线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55311103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com