coroutine.hpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. // Use this version from the top level; i.e., not running in a coroutine
  8. // itself
  9. inline void run_coroutines(MPCTIO &tio, std::vector<coro_t> &coroutines) {
  10. // Loop until all the coroutines are finished
  11. bool finished = false;
  12. while(!finished) {
  13. // If this current function is not itself a coroutine (i.e.,
  14. // this is the top-level function that launches all the
  15. // coroutines), here's where to call send(). Otherwise, call
  16. // yield() here to let other coroutines at this level run.
  17. tio.send();
  18. finished = true;
  19. for (auto &c : coroutines) {
  20. // This tests if coroutine c still has work to do (is not
  21. // finished)
  22. if (c) {
  23. finished = false;
  24. // Resume coroutine c from the point it yield()ed
  25. c();
  26. }
  27. }
  28. }
  29. }
  30. // Use this version if a coroutine needs to itself use multiple
  31. // subcoroutines.
  32. inline void run_coroutines(yield_t &yield, std::vector<coro_t> &coroutines) {
  33. // Loop until all the coroutines are finished
  34. bool finished = false;
  35. while(!finished) {
  36. // If this current function is not itself a coroutine (i.e.,
  37. // this is the top-level function that launches all the
  38. // coroutines), here's where to call send(). Otherwise, call
  39. // yield() here to let other coroutines at this level run.
  40. yield();
  41. finished = true;
  42. for (auto &c : coroutines) {
  43. // This tests if coroutine c still has work to do (is not
  44. // finished)
  45. if (c) {
  46. finished = false;
  47. // Resume coroutine c from the point it yield()ed
  48. c();
  49. }
  50. }
  51. }
  52. }
  53. #endif