如何在CPython中实现生成器和协程? [英] How are generators and coroutines implemented in CPython?

查看:93
本文介绍了如何在CPython中实现生成器和协程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经读到在CPython中,解释器堆栈(为此目的而调用的Python函数列表)与C堆栈(在解释器自己的代码中调用的C函数列表)混合在一起。如果是这样,那么如何实现生成器和协程?他们如何记住执行状态? CPython是否将每个生成器/协程的堆栈复制到OS堆栈或从OS堆栈复制?还是CPython只是将生成器的最顶层堆栈框架保留在堆上,因为生成器只能从该最顶层的框架中屈服?

I've read that in CPython, the interpreter stack (the list of Python functions called to reach this point) is mixed with the C stack (the list of C functions that were called in the interpreter's own code). If so, then how are generators and coroutines implemented? How do they remember their execution state? Does CPython copy each generator's / coroutine's stack to and from an OS stack? Or does CPython simply keep the generator's topmost stack frame on the heap, since the generator can only yield from that topmost frame?

推荐答案

yield 指令将当前正在执行的上下文作为闭包,并将其转换为自己的活动对象。该对象具有 __ iter __ 方法,该方法将在此yield语句之后继续。

The yield instruction takes the current executing context as a closure, and transforms it into an own living object. This object has a __iter__ method which will continue after this yield statement.

因此,调用堆栈被转换为堆对象。

So the call stack gets transformed into a heap object.

这篇关于如何在CPython中实现生成器和协程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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