Recently i was interested in how I could implement a simple coroutine solution
in C++. I wanted to use it for StarCraft AI Development.
I tried to find a solution for coroutines in c++ that was simple and easy to
use. I found the cross platform fibers/coroutines in
c++ library that seemed
nice but was old, so i continued looking. They mentioned
boost::execution_context as a portable alternative so I decided to give that
a try.
The interface for boost::execution_context seemed simple enough so I used
that to implement a simple coroutine class around it.
To implement a coroutine with my solution one just has to derive from the
Coroutine class and override the run() method. One can use the yield()
method to yield the current coroutine. When the coroutine is resumed with
resume() it continues after the last yield() call. A coroutine can also be
aborted with abort(). In that case the last yield() will throw
CoroutineAbortedException() and make sure that the stack is unwound and return
from the coroutine.
Example coroutine:
Example usage:
Full source code for the Coroutine implementation: