gpt4 book ai didi

kotlin - 暂停功能 block 主线程

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

我很难理解协程。这是一个非常简单的设置。 longComputationdelay 都是挂起函数。第一个阻塞主线程,后者不阻塞。为什么?

CoroutineScope(Dispatchers.Main).launch {
val result = longComputation() // Blocks
delay(10_000) // Doesn't block
}

最佳答案

这取决于。 longComputation 究竟做了什么?当您将函数标记为 suspend 时,这并不意味着您不能在其中包含阻塞代码。例如,看看这个:

suspend fun blockingSuspendFunction(){
BigInteger(1500, Random()).nextProbablePrime()
}

suspend 函数中的代码显然是利用 CPU 并阻止调用者的代码。按照惯例,不应这样做,因为如果您调用挂起函数,您期望不会阻塞线程:

Convention: suspending functions do not block the caller thread. (https://medium.com/@elizarov/blocking-threads-suspending-coroutines-d33e11bf4761)

要使这样的函数“表现为一个挂起函数”,必须将阻塞分派(dispatch)到另一个工作线程,(根据推荐)应该使用 withContext 发生:

suspend fun blockingSuspendFunction() = withContext(Dispatchers.Default) {
BigInteger.probablePrime(2048, Random())
}

关于kotlin - 暂停功能 block 主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55010765/

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