基于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_cb.cpp 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. 
  2. #include <chrono>
  3. #include <iostream>
  4. #include <string>
  5. #include <conio.h>
  6. #include <thread>
  7. #include "librf.h"
  8. using namespace resumef;
  9. template<class _Ctype>
  10. static void callback_get_long(int64_t val, _Ctype&& cb)
  11. {
  12. using namespace std::chrono;
  13. std::thread([val, cb = std::forward<_Ctype>(cb)]
  14. {
  15. std::this_thread::sleep_for(500ms);
  16. cb(val * val);
  17. }).detach();
  18. }
  19. //这种情况下,没有生成 frame-context,因此,并没有promise_type被内嵌在frame-context里
  20. static future_t<int64_t> async_get_long(int64_t val)
  21. {
  22. resumef::awaitable_t<int64_t> awaitable;
  23. callback_get_long(val, [awaitable](int64_t val)
  24. {
  25. awaitable.set_value(val);
  26. });
  27. return awaitable.get_future();
  28. }
  29. static future_t<int64_t> wait_get_long(int64_t val)
  30. {
  31. co_return co_await async_get_long(val);
  32. }
  33. //这种情况下,会生成对应的 frame-context,一个promise_type被内嵌在frame-context里
  34. static future_t<int64_t> resumable_get_long(int64_t val)
  35. {
  36. std::cout << val << std::endl;
  37. val = co_await wait_get_long(val);
  38. std::cout << val << std::endl;
  39. val = co_await wait_get_long(val);
  40. std::cout << val << std::endl;
  41. val = co_await wait_get_long(val);
  42. std::cout << val << std::endl;
  43. co_return val;
  44. }
  45. static future_t<int64_t> loop_get_long(int64_t val)
  46. {
  47. std::cout << val << std::endl;
  48. for (int i = 0; i < 5; ++i)
  49. {
  50. val = co_await async_get_long(val);
  51. std::cout << val << std::endl;
  52. }
  53. co_return val;
  54. }
  55. void resumable_main_cb()
  56. {
  57. //由于使用者可能不能明确的区分是resume function返回的awaitor还是awaitable function返回的awaitor
  58. //导致均有可能加入到协程里去调度。
  59. //所以,协程调度器应该需要能处理这种情况。
  60. go async_get_long(3);
  61. resumef::this_scheduler()->run_until_notask();
  62. GO
  63. {
  64. auto val = co_await resumable_get_long(2);
  65. std::cout << "GO:" << val << std::endl;
  66. };
  67. go loop_get_long(3);
  68. resumef::this_scheduler()->run_until_notask();
  69. }