Coroutine vs Event driven programming
Asked Answered
T

2

8

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?

Theodoretheodoric answered 13/2, 2011 at 10:4 Comment(0)
I
7

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".

Indole answered 13/2, 2011 at 10:25 Comment(0)
I
3

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.

Ilan answered 26/8, 2019 at 17:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.