协同程序中的方法在Kotlin中如何工作? [英] How does method in coroutine block work in Kotlin?

查看:79
本文介绍了协同程序中的方法在Kotlin中如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

协程有两种类型.堆叠式和无堆叠式.Kotlin协程是无堆栈协程.

Coroutine has two types. Stackful and Stackless. And Kotlin coroutine is stackless coroutine.

另一方面,一旦方法被调用,它将被堆积在内存中.我们可以使用method进行递归调用.

On the other hand, once a method gets called it is stacked on the memory. And we can do recursive calling with method.

在Kotlin中,我要做的就是为在协程环境中调用的方法添加 suspend 关键字.

And in Kotlin, all I need to do is adding suspend keyword for the methods that are called in coroutine context.

它没有堆栈,那么它如何工作?

It doesn't have a stack, then how does it work?

我想的是,由于协程对象属于某个线程,因此线程拥有它们.可以说,是的.那它如何在引擎盖下工作?

What I am guessing is, since coroutine Object belongs to a certain thread, the thread have them. Let's say, yes it is. Then how does it work under the hood?

推荐答案

Kotlin协程实际上是堆叠式和非堆叠式的混合体.对于每个函数调用,都有一个常规的Java堆栈框架.当您从 suspend fun 调用 suspend fun 时,JVM堆栈会以通常的方式增长,并且如果调用返回而没有任何暂停发生,则堆栈也会在普通状态下展开JVM方式.

Kotlin coroutines are actually a hybrid between stackful and stackless. For every function invocation there is a regular Java stack frame. When you invoke a suspend fun from a suspend fun, the JVM stack grows the usual way, and if the call returns without any suspension happening, the stack unwinds also in the common JVM way.

函数挂起时,情况会有所不同.届时,Java方法将返回并且JVM堆栈将释放.但是,在建立呼叫链的同时,还形成了另一个堆上结构: Continuation 对象的链表.每次 suspend fun 调用都会创建另一个这样的对象,您可以将其视为堆栈框架(它包含所有局部变量的值),但是在字节码级别上作为常规Java对象实现.

Things become different when a function suspends. At that point, the Java methods return and the JVM stack unwinds. However, while the call chain was being built up, another, on-heap structure was being formed: a linked list of Continuation objects. Every suspend fun invocation creates another such object, which you can think of as a stack frame (it contains the values of all the local variables), but implemented at the bytecode level, as a regular Java object.

Continuation 链是无堆栈"链,Kotlin协程的一个方面.恢复继续时,您将输入最里面的函数调用(包含函数挂起的位置).当该函数要返回时,它不会以正常方式返回,而是将恢复其调用者的继续.这将在调用方中重复,因此,当您在进行暂停乐趣调用栈时,您还将在进行JVM调用堆栈:JVM堆栈随着可挂函数的返回而增长.

This Continuation chain is the "stackless" aspect of Kotlin coroutines. When you resume a continuation, you'll enter the innermost function call (containing the location where the function suspended). When that function wants to return, it won't return the normal way, instead it will resume its caller's continuation. This will repeat in the caller, and so as you travel up the suspend fun call stack, you'll be also traveling down the JVM call stack: the JVM stack grows as the suspendable functions return.

这篇关于协同程序中的方法在Kotlin中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆