我不确定yield函数的目的是什么.你能看看我举的这个例子吗?

我正在遵循一个here的例子.

以下是代码:

val job = launch {
    val child = launch {
        try {
            delay(Long.MAX_VALUE)
        } finally {
            println("Child is cancelled")
        }
    }
    yield() //why do i need this ???????
    println("取消子项")
    child.cancel()
    child.join()
    yield()
    println("家长没有被取消")
}
job.join()

When I comment out the first yield I get the following results:

  • 取消子项

    家长没有被取消

但如果我保持yield 率不变:

  • 取消子项

    Child is cancelled

    家长没有被取消

What does it mean to use yield here?

推荐答案

https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/yield.html

Yields a thread (or thread pool) of the current coroutine dispatcher to other coroutines to run. If the coroutine dispatcher does not have its own thread pool (like Dispatchers.Unconfined) then this function does nothing, but checks if the coroutine Job was completed. This suspending function is cancellable. If the Job of the current coroutine is cancelled or completed when this suspending function is invoked or while this function is waiting for dispatching, it resumes with CancellationException.

它至少可以完成一些事情

  1. It temporarily deprioritises the current long running CPU task, giving other tasks a fair opportunity to run.
  2. Checks whether the current job is cancelled, since otherwise in a tight CPU bound loop, the job may not check until the end.
  3. 允许子作业(job)的进度,其中存在争用,因为作业(job)比线程多.如果当前工作应根据其他工作的进展进行调整,这一点可能很重要.

Kotlin相关问答推荐

使用Jackson反序列化HTML列表时出现MismatchedInputResponse

在没有外部 map 的情况下转换列表项

Lambda和普通Kotlin函数有什么区别?

在KMP中使用koin将来自Android的上下文注入到SQLDelight Driver中

在intellij中使用kotlin符号和floordiv

如何定义一个函数来接受任何具有特定字段的数据类

Kotlin - 什么时候和什么时候不喜欢内联函数,为什么?

限制通用Kotlin枚举为特定类型

在 detekt 配置文件中找不到某些属性

区分函数和扩展

Kotlin 协程按顺序执行,但仅在生产机器上执行

如何通过 compose 处理剪切区域?

在 Kotlin 中,::class.simpleName是做什么的?

错误:cannot find symbol import com.gourav.news.databinding.ActivityDetailBindingImpl;

无法删除部分子项.这可能是因为进程打开了文件或将其工作目录设置在目标目录中

Kotlin:泛型、反射以及类型 T 和 T:Any 之间的区别

创建首选项屏幕时找不到androidx.preference.PreferenceScreen

Intellij 显示 build.gradle.kts 中的每一行都是红色的

Kotlin - 错误:Could not find or load main class _DefaultPackage

为什么 Kotlin 会收到这样的 UndeclaredThrowableException 而不是 ParseException?