coroutine.hpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #ifndef __COROUTINE_HPP__
  2. #define __COROUTINE_HPP__
  3. #include <vector>
  4. #include <boost/coroutine2/coroutine.hpp>
  5. typedef boost::coroutines2::coroutine<void>::pull_type coro_t;
  6. typedef boost::coroutines2::coroutine<void>::push_type yield_t;
  7. // The top-level coroutine runner will call run_coroutines with
  8. // a MPCTIO, and we should call its send() method. Subcoroutines that
  9. // launch their own coroutines (and coroutine running) will call
  10. // run_coroutines with a yield_t instead, which we should just call, in
  11. // order to yield to the next higher level of coroutine runner.
  12. static inline void send_or_yield(MPCTIO &tio) { tio.send(); }
  13. static inline void send_or_yield(yield_t &yield) { yield(); }
  14. template <typename T>
  15. inline void run_coroutines(T &mpctio_or_yield, std::vector<coro_t> &coroutines) {
  16. // Loop until all the coroutines are finished
  17. bool finished = false;
  18. while(!finished) {
  19. // If this current function is not itself a coroutine (i.e.,
  20. // this is the top-level function that launches all the
  21. // coroutines), here's where to call send(). Otherwise, call
  22. // yield() here to let other coroutines at this level run.
  23. send_or_yield(mpctio_or_yield);
  24. finished = true;
  25. for (auto &c : coroutines) {
  26. // This tests if coroutine c still has work to do (is not
  27. // finished)
  28. if (c) {
  29. finished = false;
  30. // Resume coroutine c from the point it yield()ed
  31. c();
  32. }
  33. }
  34. }
  35. }
  36. #endif