Thursday, March 31, 2016

Variation to a theme: Subtraction

Thoughts on async programming and Coroutines vs Generators vs Continuations

Here is my understanding of these related ideas.

Here is a model for async programming , where the + is the event loop. I think that one could use such kind of diagrams to model a async call model e.g. as one finds in Javascript, or as one constructs using libevent.



On a slightly different topic about continuations, co-routines, generators and functions, i look upon them as the following. This is still work in progress and I will update as my understanding improves. Something to begin with as a note:



Following is a quick note about how generators exist in python:
Generators in Python:

I have worked with generators in the context of RtmpLite

Generators are used to write non-blocking I/O in synchronous style without all the nesting etc that comes with asynchronous programming.  (ref: http://calculist.org/blog/2011/12/14/why-coroutines-wont-work-on-the-web/) . As shown below, the sleep(1000) will invoke a timer on the event loop and the control will yield back to the caller. Eventually, when the timer event triggers it will be added to the event queue and be executed starting off from where it left.

1
2
3
4
5
Task(function() {
    console.log('wait... ' + new Date);
    yield sleep(1000);
    console.log('ok... ' + new Date);
}).run();