Reputation: 107
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?
Upvotes: 2
Views: 1823
Reputation: 148169
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.
Upvotes: 2