codepad
[
create a new paste
]
login
|
about
Language:
C
C++
D
Haskell
Lua
OCaml
PHP
Perl
Plain Text
Python
Ruby
Scheme
Tcl
#include <stdio.h> // for printf #include <memory.h> // for memcpy #include <setjmp.h> // for setjmp template <typename T> struct coroutine { volatile int state; coroutine():state(0){} volatile char *stkptrH,*stkptrL; jmp_buf PointA,PointB; char stack[1<<10]; void yield( int value ) { char curtmp; stkptrL=(&curtmp)-16; if(setjmp(PointB)==0) state=value,memcpy(stack,(char*)stkptrL,stkptrH-stkptrL),longjmp(PointA,1); } __attribute__((noinline)) int call_do_process() { char stktmp[1<<16];stkptrH=stktmp;((T*)this)->do_process();return 0;} int call() {if(setjmp(PointA)==0)(state?memcpy((char*)stkptrL,stack,stkptrH-stkptrL),longjmp(PointB,1):void(0)),call_do_process();return state;} }; struct Index : coroutine<Index> { void do_process( void ) { for( int a=1;; ) { yield( a ); a++; } }} F1; struct Fibonacci : coroutine<Fibonacci> { void do_process( void ) { for( int a=0,b=1;; ) { yield( b ); b = b + a; a = b - a; } }} F2; int main( void ) { for( int i=0; i<20; i++ ) { printf( "%i:%i ", F1.call(), F2.call() ); } printf( "\n" ); return 0; }
Private
[
?
]
Run code
Submit