启动协程构建器是否会导致在新线程上将函数暂停到 运行?
does launch coroutine builder cause suspend functions to run on new thread?
最近开始使用 Kotlin 协程
语法如下:
main(){
launch(Dispatchers.Main){
delay(2000)
print("inside coroutine")
}
print("outside coroutine")
}
我知道首先打印外部协程,然后打印内部协程,因为延迟是一个挂起函数,它只阻塞协程而不阻塞线程本身。
但是由于协程需要在其他地方(比如在不同的线程上)执行才能知道何时恢复,这是如何处理的?
它可以是任何进程强烈的暂停功能而不是延迟。
我唯一无法理解的是,无论 launch{} 构建器中提供的 Dispatcher 是什么,挂起函数实际上 运行 是否在幕后的不同线程上?
delay() 函数在后台是 运行 异步的。如果 运行 使用 Dispatchers.Main
,其他挂起函数将阻塞线程
suspend
函数旨在阻塞当前协程,而不是线程,这意味着它们应该 运行 在后台线程中。例如 delay
函数在给定时间内阻塞协程而不阻塞线程并在指定时间后恢复它。您可以创建一个 suspend
函数,它 运行 在后台线程上运行,如下所示:
suspend fun someSuspendFun() = withContext(Dispatchers.IO) {
// do some long running operation
}
使用withContext(Dispatchers.IO)
我们将函数执行的上下文切换到后台线程。 withContext
函数也可以 return 一些结果。
要调用该函数,我们可以使用协程构建器:
someScope.launch(Dispatchers.Main){
someSuspendFun() // suspends current coroutine without blocking the Main Thread
print("inside coroutine") // this line will be executed in the Main Thread after `someSuspendFun()` function finish execution.
}
最近开始使用 Kotlin 协程
语法如下:
main(){
launch(Dispatchers.Main){
delay(2000)
print("inside coroutine")
}
print("outside coroutine")
}
我知道首先打印外部协程,然后打印内部协程,因为延迟是一个挂起函数,它只阻塞协程而不阻塞线程本身。
但是由于协程需要在其他地方(比如在不同的线程上)执行才能知道何时恢复,这是如何处理的?
它可以是任何进程强烈的暂停功能而不是延迟。
我唯一无法理解的是,无论 launch{} 构建器中提供的 Dispatcher 是什么,挂起函数实际上 运行 是否在幕后的不同线程上?
delay() 函数在后台是 运行 异步的。如果 运行 使用 Dispatchers.Main
,其他挂起函数将阻塞线程suspend
函数旨在阻塞当前协程,而不是线程,这意味着它们应该 运行 在后台线程中。例如 delay
函数在给定时间内阻塞协程而不阻塞线程并在指定时间后恢复它。您可以创建一个 suspend
函数,它 运行 在后台线程上运行,如下所示:
suspend fun someSuspendFun() = withContext(Dispatchers.IO) {
// do some long running operation
}
使用withContext(Dispatchers.IO)
我们将函数执行的上下文切换到后台线程。 withContext
函数也可以 return 一些结果。
要调用该函数,我们可以使用协程构建器:
someScope.launch(Dispatchers.Main){
someSuspendFun() // suspends current coroutine without blocking the Main Thread
print("inside coroutine") // this line will be executed in the Main Thread after `someSuspendFun()` function finish execution.
}