不可预测的协程执行顺序?

Unpredictable coroutines execution order?

这是我的想法: 当使用协同程序时,你会堆积异步操作,一旦你完成了同步操作..按 FIFO 顺序调用它们..但这并不总是正确的

在这个例子中你得到了我所期望的:

fun main() = runBlocking {
   launch {
      println("1")
   }

   launch {
      println("2")
   }

   println("0")
}

也在这里(嵌套启动):

fun main() = runBlocking {
   launch {
      println("1")
   }

   launch {
      launch {
         println("3")
      }

      println("2")
   }

   println("0")
}

现在在这个例子中有一个范围构建器并创建另一个"pile"(不是真正的术语)顺序改变了但仍然..你得到预期的

fun main() = runBlocking {
   launch {
      println("2")
   }

   // replacing launch
   coroutineScope {
      println("0")
   }

   println("1")
}

最后..这个问题的原因..示例 2 with scope builder:

fun main() = runBlocking {
   launch {
      println("3")
   }

   coroutineScope {
      launch {
         println("1")
      }

      println("0")
   }

   println("2")
}

我明白了: 0 3个 1个 2

为什么??

我的假设错了吗,协程不是这样工作的

如果是..那我编码时应该如何确定正确的顺序

编辑:我试过运行在不同的机器和不同的平台上使用相同的代码,但总是得到相同的结果..还尝试了更复杂的嵌套来证明结果的不变性

并且翻文档发现协程只是代码转换(正如我最初认为的那样)

记住,即使喜欢调用它们 'light-weight' 线程,它们 运行 在单个 'real' 线程中(注意:没有 newSingleThreadContext)

因此我选择相信执行顺序是在编译时预先确定的,而不是在运行时

决定的

毕竟..我还是无法预料顺序..这就是我想要的

不要假设协程将 运行 以特定顺序排列,运行时间将决定 运行 的最佳时间和顺序。您可能感兴趣的是 kotlinx.coroutines documentation. It does a great job of explaining how they work and also provides some handy abstractions to help managing coroutines make more sense. I personally recommend checking out channels, jobs, and Deferred (async/await).

例如,如果我希望事情按编号的特定顺序完成,我会使用渠道来确保事情按我想要的顺序到达。

runBlocking {
    val channel = Channel<Int>()
    launch {
        for (x in 0..5) channel.send(x * x)
        channel.close()
    }

    for (msg in channel) {
        // Pretend we're doing some work with channel results
        println("Message: $msg")
    }
}

希望这可以为您提供更多背景信息,或者协程是什么以及它们有什么用处。