Monday, November 15, 2010


Today we talked a little about coroutines, at first glance based on the slides it seemed like they were saying that the coroutines would start at the beginning and end when they return, this was a little confusing as they seemed to be identical to procedures.

Turns out we were misunderstanding the picture.

From Wikipedia:
In computer science, coroutines are program components that generalize subroutines to allow multiple entry points for suspending and resuming execution at certain locations. Coroutines are well-suited for implementing more familiar program components such as cooperative tasksiteratorsinfinite lists and pipes.

So what is a Coroutine? Well think of it this way, suppose we have a few programs running in threads, and we have an operating system. Do you think the operating system calls each of these threads to do some work, and when it has to pause and stop to go do something it just starts what it was doing all over again? We wouldn't ever get anything accomplished in computing if that was the case. This is where coroutines come into play, since we can return to the last context that was running we can just keep on running. For example, suppose we have a thread that runs a REALLY LONG for loop, the OS does a context switch and pushes the current status onto the stack. Another thread does some work then returns (or perhaps another thread needs servicing). Upon return all the data that was in use from the function is popped from the stack and back in use again. 

Now the book describes the process in a little more detail, but basically what's happening is that the next address is being pushed to the stack, then the operating system goes off and does some stuff, and pops the address off back into the program counter, and the function keeps running as if nothing happened (to it, the change was transparent).

I hope that helped ya out, let me know if you have any questions.