stackoverflow :
http://stackoverflow.com/questions/4352451/coroutine-demo-source-2/4352706#4352706
and the work source :
#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;
}
Output :
1:1 2:1 3:2 4:3 5:5 6:8 7:13 8:21 9:34 10:55 11:89 12:144 13:233 14:377 15:610 16:987 17:1597 18:2584 19:4181 20:6765
留言列表