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 exhasted it's 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.