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