Since I used coroutines only on JVM, I will talk about JVM backend, there are also Kotlin Native and Kotlin JavaScript but these backends for Kotlin are out of my scope.
So let's start with comparing Kotlin coroutines to other languages coroutines. Basically, you should know that there are two types of Coroutines: stackless and stackful. Kotlin implements stackless coroutines - it means that coroutine doesn't have its own stack, and that limiting a little bit what coroutine can do. You can read a good explanation here.
Examples:
- Stackless:C#,Scala,Kotlin
- Stackful: Quasar, Javaflow
协程就像轻线是什么意思?
这意味着Kotlin中的协程没有自己的堆栈,它不映射到本机线程,它不需要处理器上的上下文切换.
有什么区别?
线程抢占式多任务处理.(usually).
协作式-协作式多任务处理.
Thread - managed by OS (usually).
Coroutine - managed by a user.
Are kotlin's coroutines actually running in parallel / concurrently?
这取决于具体情况,您可以在自己的线程中运行每个协程,也可以在一个线程或某个固定线程池中运行所有协程.
More about how coroutines execute here.
即使在多核系统中,在任何给定的时间也只有一个协同程序在运行(对吗?)
不,请参见前面的答案.
Here I'm starting 100000 coroutines, what happens behind this code?
Actually, it depends. But assume that you write the following code:
fun main(args: Array<String>) {
for (i in 0..100000) {
async(CommonPool) {
delay(1000)
}
}
}
This code executes instantly.
因为我们需要等待async
电话的结果.
So let's fix this:
fun main(args: Array<String>) = runBlocking {
for (i in 0..100000) {
val job = async(CommonPool) {
delay(1)
println(i)
}
job.join()
}
}
当您运行此程序时,kotlin将创建2*Continuation
000个Continuation
实例,这将占用几十Mb的内存,并且在控制台中,您将看到从1到Continuation
000的数字.
So lets rewrite this code in this way:
fun main(args: Array<String>) = runBlocking {
val job = async(CommonPool) {
for (i in 0..100000) {
delay(1)
println(i)
}
}
job.join()
}
我们现在取得了什么成就?现在,我们只创建了Continuation
001个Continuation
个实例,这要好得多.
Each created Continuation will be dispatched and executed on CommonPool (which is a static instance of ForkJoinPool).