基于C++ Coroutines提案 ‘Stackless Resumable Functions’编写的协程库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_async_yield_return.cpp 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #include <chrono>
  2. #include <iostream>
  3. #include <string>
  4. #include <thread>
  5. #include "librf/librf.h"
  6. using namespace librf;
  7. generator_t<int> test_yield_int()
  8. {
  9. std::cout << "1 will yield return" << std::endl;
  10. co_yield 1;
  11. std::cout << "2 will yield return" << std::endl;
  12. co_yield 2;
  13. std::cout << "3 will yield return" << std::endl;
  14. co_yield 3;
  15. std::cout << "4 will return" << std::endl;
  16. co_return 4;
  17. std::cout << "5 will never yield return" << std::endl;
  18. co_yield 5;
  19. }
  20. /*不能编译*/
  21. /*
  22. auto test_yield_void()
  23. {
  24. std::cout << "1 will yield return" << std::endl;
  25. co_yield ;
  26. std::cout << "2 will yield return" << std::endl;
  27. co_yield ;
  28. std::cout << "3 will yield return" << std::endl;
  29. co_yield ;
  30. std::cout << "4 will return" << std::endl;
  31. co_return ;
  32. std::cout << "5 will never yield return" << std::endl;
  33. co_yield ;
  34. }
  35. */
  36. auto test_yield_void() -> generator_t<>
  37. {
  38. std::cout << "block 1 will yield return" << std::endl;
  39. co_yield_void;
  40. std::cout << "block 2 will yield return" << std::endl;
  41. co_yield_void;
  42. std::cout << "block 3 will yield return" << std::endl;
  43. co_yield_void;
  44. std::cout << "block 4 will return" << std::endl;
  45. co_return_void;
  46. std::cout << "block 5 will never yield return" << std::endl;
  47. co_yield_void;
  48. }
  49. auto test_yield_future() -> future_t<int64_t>
  50. {
  51. std::cout << "future 1 will yield return" << std::endl;
  52. co_yield 1;
  53. std::cout << "future 2 will yield return" << std::endl;
  54. co_yield 2;
  55. std::cout << "future 3 will yield return" << std::endl;
  56. co_yield 3;
  57. std::cout << "future 4 will return" << std::endl;
  58. co_return 4;
  59. std::cout << "future 5 will never yield return" << std::endl;
  60. co_yield 5;
  61. }
  62. void resumable_main_yield_return()
  63. {
  64. std::cout << __FUNCTION__ << std::endl;
  65. for (int i : test_yield_int())
  66. {
  67. std::cout << i << " had return" << std::endl;
  68. }
  69. go test_yield_int();
  70. this_scheduler()->run_until_notask();
  71. go test_yield_void();
  72. this_scheduler()->run_until_notask();
  73. go test_yield_future();
  74. this_scheduler()->run_until_notask();
  75. }
  76. #if LIBRF_TUTORIAL_STAND_ALONE
  77. int main()
  78. {
  79. resumable_main_yield_return();
  80. return 0;
  81. }
  82. #endif