简体   繁体   中英

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

My understanding of Kotlin coroutines and thread is this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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