In The Art of Computer Programming
, Donald Knuth
, presents the idea of co-routines.
Basically, a more enhanced idea of a subroutine, which allows a function to preserve its state between calls, behaving more like a generator. Co-routines make it easier to write state-driven programs. Instead of maintaining the state manually, the programmer splits the execution into threads, letting the execution stack preserve the program's states.
It's easy to give an example to coroutines, using Python's future keyword: yield. I'll illustrate:
def fibonacci(a=1, b=1):
c = a + b
a = b
b = c
generator = fibonacci()
print "First fibonacci: ", generator.next()
print "Second fibonacci: ", generator.next()
print "Third fibonacci: ", generator.next()
print "Fourth fibonacci: ", generator.next()
print "Fifth fibonacci: ", generator.next()
Running the code above will output:
First fibonacci: 1
Second fibonacci: 1
Third fibonacci: 2
Fourth fibonacci: 3
Fifth fibonacci: 5
In this example, the entire internal state
() is stored in the 'generator' object. On every next(), the function's execution
continues until the next 'yield'. The parameter given to yield is returned by next().
It's possible to implement this in other langauges such
as C and C++, using setjmp(), longjmp(), and stack-switching methods. This was already been done through the implementation of the various lightweight threads libraries, such as the Windows Fiber library.