简体   繁体   English

启动协程生成器会导致挂起函数在新线程上运行吗?

[英]does launch coroutine builder cause suspend functions to run on new thread?

Started using Kotlin coroutines recently最近开始使用 Kotlin 协程

here is the syntax:这是语法:

main(){
launch(Dispatchers.Main){
    delay(2000)
    print("inside coroutine")
}
print("outside coroutine")
}

I understand that outside coroutine is printed first and then inside coroutine is printed because delay is a suspend function and it blocks the coroutine only and not the thread itself.我知道首先打印外部协程,然后打印内部协程,因为延迟是暂停 function 并且它仅阻止协程而不是线程本身。

But as the coroutine would need to be executed somewhere else(like on a different thread) for it to know when to resume, how is this taken care of?但是由于协程需要在其他地方(例如在不同的线程上)执行才能知道何时恢复,所以这是如何处理的?

It can be any process intense suspend function instead of delay.它可以是任何进程强烈暂停 function 而不是延迟。

Only thing I can't understand is Does the suspend function actually run on a different thread under the hood irrespective of the Dispatcher provided in launch{} builder?唯一我不明白的是,无论启动{}构建器中提供的调度程序如何,挂起 function 是否实际上在引擎盖下的不同线程上运行?

delay() function is run asynchronously under the hood. delay() function 在后台异步运行。 Other suspend functions would block the thread if run using Dispatchers.Main如果使用 Dispatchers.Main 运行,其他挂起函数会阻塞线程

suspend functions are designed to block current coroutine, not the thread, it means they should run in background thread. suspend函数旨在阻止当前协程,而不是线程,这意味着它们应该在后台线程中运行。 For example delay function blocks coroutine for a given time without blocking a thread and resumes it after a specified time.例如delay function 在给定时间内阻塞协程而不阻塞线程,并在指定时间后恢复它。 You can create a suspend function which runs on background thread like the following:您可以创建一个在后台线程上运行的suspend function,如下所示:

suspend fun someSuspendFun() = withContext(Dispatchers.IO) {
    // do some long running operation
}

Using withContext(Dispatchers.IO) we switch the context of function execution to background thread.使用withContext(Dispatchers.IO)我们将 function 执行的上下文切换到后台线程。 withContext function also can return some result. withContext function 也可以返回一些结果。

To call that function we can use a coroutine builder:要调用 function,我们可以使用协程构建器:

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.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM