fork download
  1. #include <stdio.h> // for printf
  2. #include <memory.h> // for memcpy
  3. #include <setjmp.h> // for setjmp
  4. template <typename T> struct coroutine {
  5. volatile int state; coroutine():state(0){}
  6. volatile char *stkptrH,*stkptrL; jmp_buf PointA,PointB; char stack[1<<10];
  7. void yield( int value ) { char curtmp; stkptrL=(&curtmp)-16; if(setjmp(PointB)==0)
  8. state=value,memcpy(stack,(char*)stkptrL,stkptrH-stkptrL),longjmp(PointA,1); }
  9. __attribute__((noinline)) int call_do_process() { char stktmp[1<<16];stkptrH=stktmp;((T*)this)->do_process();return 0;}
  10. int call() {if(setjmp(PointA)==0)(state?memcpy((char*)stkptrL,stack,stkptrH-stkptrL),longjmp(PointB,1):void(0)),call_do_process();return state;}
  11. };
  12.  
  13. struct Index : coroutine<Index> { void do_process( void ) {
  14. for( int a=1;; ) { yield( a ); a++; }
  15. }} F1;
  16.  
  17. struct Fibonacci : coroutine<Fibonacci> { void do_process( void ) {
  18. for( int a=0,b=1;; ) { yield( b ); b = b + a; a = b - a; }
  19. }} F2;
  20.  
  21. int main( void ) {
  22. for( int i=0; i<20; i++ ) {
  23. printf( "%i:%i ", F1.call(), F2.call() );
  24. } printf( "\n" );
  25. return 0;
  26. }
Success #stdin #stdout 0s 2896KB
stdin
Standard input is empty
stdout
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