You might want to take a look at:
That goes with threading, not sure if want to go there, but some of the concepts might work well for the single thread case.