Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

An alternative approach, arguably with too much magic: http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html


Actually, the link you've posted is much simpler than the parent post: no assembly voodo required and no longjump shenanigans. It's also much easier to debug under a debugger. I've successfully used this in production code. It effectively boils down to these 3 defines:

  #define COR_BEGIN(stateVar)            switch(stateVar) { case 0:;
  #define COR_END(stateVar)              }; stateVar = -1;
  #define COR_RETURN(stateVar)           do { stateVar=__LINE__; return; case __LINE__:;} while (0)

  void dofunc(int* pstate)
  {
   COR_BEGIN(*pstate);

   while (computation1)
       COR_RETURN(*pstate);

   while (computation2)
       COR_RETURN(*pstate);

   COR_END(*pstate);
  }


No stack though, so you can't have arbitrary code running in several concurrently executing coroutines.

As to debugging, I don't think setjmp/longjmp gets in the way of debuggers at all.




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: