#include #include struct Fibonacci { coroutine c; coVtable v; int fn; // used for communication }; coroutine* this_coroutine(Fibonacci* this); void co_main(Fibonacci* this); coVtable* vtable(Fibonacci* this); void co_main_fib(void* this) { co_main( (Fibonacci*) this ); } coroutine* this_coroutine_fib(void* this) { return this_coroutine( (Fibonacci*) this); } void ?{}(Fibonacci* this) { this->fn = 0; this->v.main = co_main_fib; this->v.this_coroutine = this_coroutine_fib; start(this); } void co_main(Fibonacci* this) { #ifdef MORE_DEBUG sout | "Starting main of coroutine " | this | endl; sout | "Started from " | this_coroutine(this)->last | endl; #endif int fn1, fn2; // retained between resumes this->fn = 0; fn1 = this->fn; suspend(); // return to last resume this->fn = 1; fn2 = fn1; fn1 = this->fn; suspend(); // return to last resume for ( ;; ) { this->fn = fn1 + fn2; fn2 = fn1; fn1 = this->fn; suspend(); // return to last resume } } int next(Fibonacci* this) { resume(this); // transfer to last suspend return this->fn; } coroutine* this_coroutine(Fibonacci* this) { return &this->c; } coVtable* vtable(Fibonacci* this) { return &this->v; } int main() { Fibonacci f1, f2; #ifdef MORE_DEBUG sout | "User coroutines : " | &f1 | ' ' | &f1 | endl; #endif for ( int i = 1; i <= 10; i += 1 ) { sout | next(&f1) | ' ' | next(&f2) | endl; } return 0; }