Overview

    libCoroutine is a simple stackfull coroutine implementation. On unix platforms, the implementation uses ucontext if available or with setjmp/longjmp otherwise except on OSX where some assembly is used. On windows, fibers are used.

    Main

    First you'll need to create a coro instance to represent the C stack that was allocated to run the host program's main() function:
    Coro *mainCoro = Coro_new();
    Coro_initializeMainCoro(mainCoro);
    

    Starting

    To create a coroutine:
    Coro *newCoro = Coro_new();
    Coro_startCoro_(currentCoro, newCoro, aContext, aCallback);
    
    currentCoro should be a pointer to the currenting running coroutine (which would be mainCoro, if this is the first corountine you're creating). aCallback is a function pointer for the function which will be called when the coroutine starts and aContext is the argument that will be passed to the callback function.

    Switching

    To switch to the coroutine:
    Coro_switchTo_(currentCoro, nextCoro);
    

    Freeing

    Coro_free(aCoro);
    
    Note that you can't free the currently running coroutine as this would free the current C stack.

    Stacks

    You can check to see whether a corouinte has nearly exhausted its stack space by calling:
    Coro_stackSpaceAlmostGone(aCoro);
    
    This returns 1 if the remaining stack space is less than CORO_STACK_SIZE_MIN.

    The define CORO_STACK_SIZE can be used to adjust the default stack size. There is also a #ifdef on USE_VALGRIND which, when enabled, will register stack switches with valgrind, so it won't be confused.

    Chaining

    A trick to provide effectively get unlimited stack space while keeping stack allocations small is to periodically call Coro_stackSpaceAlmostGone() and create a new Coro in which to continue the computation when the stack gets low.

    Credits

    I (Steve Dekorte) mostly just put together bits of code from other folks to make this library. Russ Cox deserves the most credit currently for the portable ucontext code. Some history:

    Originally based on Edgar Toernig's Minimalistic cooperative multitasking (http://www.goron.de/~froese/)
    reorg by Steve Dekorte and Chis Double
    Symbian and Cygwin support by Chis Double
    Linux/PCC, Linux/Opteron, Irix and FreeBSD/Alpha, ucontext support by Austin Kurahone
    FreeBSD/Intel support by Faried Nawaz
    Mingw support by Pit Capitain
    Visual C support by Daniel Vollmer
    Solaris support by Manpreet Singh
    Fibers support by Jonas Eschenburg
    Ucontext arg support by Olivier Ansaldi
    Ucontext x86-64 support by James Burgess and Jonathan Wright
    Russ Cox for the newer portable ucontext implementions.