基于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.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include <chrono>
  2. #include <iostream>
  3. #include <string>
  4. #include <conio.h>
  5. #include <thread>
  6. #include "librf.h"
  7. using namespace resumef;
  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. 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. }