科特林协程。 launch{fun} 和 launch{suspend fun} 的区别

kotlin coroutines. Difference between launch{ fun} and launch {suspend fun}

两者在执行上有什么不同吗?

launch {
    function1()
}
fun function1(){
    DoSomething...
}

launch {
   function2()
}
suspend fun function2(){
   DoSomething...
}

是的,有。

从语义上讲,对挂起函数的调用可能会挂起执行,这可能会在稍后(或永远不会)的某个时间点恢复,可能在不同的上下文中(例如另一个线程)。

为了确保这一点,编译器以一种特殊的方式处理对挂起函数的调用:它生成将当前局部变量保存到 Continuation 实例中的代码,并将其传递给挂起函数,并且有也是调用后字节码中的一个恢复点,执行将跳转到该点,加载局部变量和 运行 on(尾调用的极端情况)。

对 non-suspending 函数的调用被编译为更简单的字节码,与通常在挂起函数体之外调用函数相同。

您可以在此处找到有关 Kotlin 协程设计和实现的详细信息:Coroutines for Kotlin

您还可以检查生成的编译字节码以查看差异:

让我加几分钱

你基本上是在问函数和挂起函数的区别。

协程就像一个线程,只是它不会占用太多计算机内存。您可以轻松启动 100,000 个协程。 挂起函数基本上只是一个函数,但具有特殊的调用范围。它只能从协程和其他挂起的函数中调用。 从 Kotlin 官方文档中,它说

Suspend functions are only allowed to be called from a coroutine or another suspend function. Let's dig a little into what it means. The biggest merit of coroutines is that they can suspend without blocking a thread. The compiler has to emit some special code to make this possible, so we have to mark functions that may suspend explicitly in the code.