协程是如何实现的?
我有一个关于协程实现的问题。 我首先在 Lua 和 stackless-python 上看到了协程。我可以理解它的概念,以及如何使用 yield
关键字,但我不知道它是如何实现的。
我可以得到一些关于它们的解释吗?
I have a question about coroutine implementation.
I saw coroutine
first on Lua and stackless-python. I could understand the concept of it, and how to use yield
keyword, but I cannot figure out how it is implemented.
Can I get some explanation about them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
协程是通过压入目标地址来启动的,然后每个协程切换与堆栈顶部交换当前PC,最终必须弹出以终止协程。
Coroutining is initiated by pushing the target address, then each coroutine switch exchanges the current PC with the top of the stack, which eventually has to get popped to terminate the coroutining.
另请参阅:以自定义语言实现“生成器”支持。生成器基本上是(半)协程的有限形式,该问题中讨论的大部分内容也适用于此处。
另外:异常是如何在幕后实现的?虽然异常显然与协程有很大不同,但它们都有一些共同点:都是先进的通用控制流结构。 (事实上,你可以使用异常来实现协程,也可以使用协程来实现异常。)
See also: Implementing “Generator” support in a custom language. Generators are basically a limited form of (semi-)coroutines, most of what is discussed in that question applies here as well.
Also: How are exceptions implemented under the hood? While exceptions are obviously very different from coroutines, they both have something in common: both are advanced universal control flow constructs. (In fact, you can implement coroutines using exceptions and exceptions using coroutines.)