Wednesday, June 6, 2012

Co-routines in C(++)

A little while ago I put together a small co-routine library in C targeting x86/Windows. It uses micro-stacks of about 4kb, minus a small tax for library overhead, for each co-routine which places some constraints on the work that can be done but I figured that it'd complement Windows' fairly heavyweight fiber library.

The code sets up a new thread context, by setting esp to point to the new co-routine stack, and then uses setjmp and longjmp to yield the co-routine to the main execution context and to resume the co-routine from where it left off.

One known issue is that if you build C++ code with Visual C++'s /EH command line options the compiler will automatically run destructors on stack objects as it unwinds past them, and so any objects you create in your co-routines will be destroyed prematurely. Building without exceptions enabled will work around this.

Code: https://github.com/maxburke/coroutine

No comments:

Post a Comment