协程与事件驱动编程
关于维基百科中的示例: http://en.wikipedia.org/wiki/Coroutine
var q := new queue
coroutine produce
loop
while q is not full
create some new items
add the items to q
yield to consume
coroutine consume
loop
while q is not empty
remove some items from q
use the items
yield
我只是想知道传统的基于事件的方法可以处理这种用法模式,为什么需要使用协程?
Regarding the example in wikipedia:
http://en.wikipedia.org/wiki/Coroutine
var q := new queue
coroutine produce
loop
while q is not full
create some new items
add the items to q
yield to consume
coroutine consume
loop
while q is not empty
remove some items from q
use the items
yield
I just wonder traditional event based approach can handle this kind of usage pattern, why need to use coroutine?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在事件驱动编程中,您正在状态机上工作,您需要显式地保留当前状态并通过使用开关或一系列回调来处理您在该状态下所做的工作。此类程序是非线性的。
在基于协程的系统中,您可以像通常编写单线程程序一样编写线性程序,但您将切换上下文并让其他组件执行其工作,直到您的事件到来,而不是在每个事件等待点阻塞。在许多基于协程的系统中,您会发现一个事件循环,它驱动协程并在事件到达时切换进出协程。
In an event-driven programming you are working on a state machine, you need to explicitly keep your current state and handle the work you are on in the state, either by using a switch or a succession of callbacks. Such programs are non-linear.
In a coroutine based system you can write a linear program like you would normally write a single-threaded one but instead of blocking at each event-waiting point you will switch the context out and let other components do their work until your event comes. In many of the coroutine based systems you will find an event loop that drives the coroutines and switches in and out of the coroutines when their event arrives.
我认为协程是“传统”的,而事件是“现代”的。然而,它们也有不同的目的; AFAIK,协程可以指定转移控制的位置(如方法调用)或用于时间共享< /a>,而事件是松散耦合的通信(即在分层架构中“向上”通信) 。
如果您想了解续传风格,请务必阅读 Eric Lippert 的博客系列(自 2010 年 10 月起)对这些事情感兴趣。有一篇文章标题为“关于协程的思考"。
I think it is coroutines that are "traditional", and events are "modern". However, they also have different purpose; AFAIK, coroutines can either specify where to transfer control (like method calls) or be used to time-share, while events are loosely coupled communication (i.e. communicating "upwards" in a layered architecture).
Be sure to read Eric Lippert's blog series (from October, 2010) about continuation passing style if you are interested in things like these. There is one post titled "Musings about coroutines".