简体   繁体   English

在 Kotlin 中,一个线程一次只能运行一个协程?

[英]In Kotlin, one thread can only run one coroutine at a time?

My understanding of Kotlin coroutines and thread is this:我对 Kotlin 协程和线程的理解是这样的:

One thread can only run one coroutine at a time.一个线程一次只能运行一个协程。 A thread can juggle multiple coroutines.一个线程可以处理多个协程。 It can suspend a coroutine and run a different coroutine.它可以挂起一个协程并运行一个不同的协程。 But at a given point in time only one coroutine will be running on a thread.但是在给定的时间点,一个线程上只会运行一个协程。 You cannot run multiple coroutines on the same thread at the same point of time.您不能在同一时间点在同一线程上运行多个协程。

Is this right?这是正确的吗?

Yes, this is correct.是的,这是正确的。

A coroutine can be seen as an instruction sequence that a thread runs until it encounters a suspension point, at which the coroutine suspends its execution (saving the call stack and local variables to be resumed later) and yields control, and in that case it no longer runs on the thread it was running on.协程可以看作是一个线程运行的指令序列,直到它遇到一个暂停点,在这个点协程暂停它的执行(保存调用堆栈和局部变量以供稍后恢复)并让出控制权,在这种情况下它没有在它运行的线程上运行更长的时间。

This is very similar to how a function that returns no longer runs on the thread, returning control to the caller, but a coroutine additionally saves its state so that it is possible to resume it later, on the same thread or another.这与返回的函数不再在线程上运行,将控制权返回给调用者的方式非常相似,但是协程另外保存了它的状态,以便以后可以在同一线程或另一个线程上恢复它。 Once a coroutine yields control, the thread returns to the code that started or resumed the coroutine.一旦协程让出控制权,线程就会返回到启动或恢复协程的代码。 That code may or may not be another coroutine.该代码可能是也可能不是另一个协程。

You can think of a thread as a primitive of a lower level (OS-level, or JVM-level) than coroutines.您可以将线程视为比协程更低级别(OS 级别或 JVM 级别)的原语。 All code in an application is executed in some thread, one instruction sequence in each thread at a time, and coroutines are no exclusion in this sense.应用程序中的所有代码都在某个线程中执行,每次在每个线程中执行一个指令序列,从这个意义上说,协程并不排斥。

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

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