基于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_event_v2.cpp 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. //非协程的逻辑线程,或异步代码,可以通过event_t通知到协程,并且不会阻塞协程所在的线程。
  9. std::thread async_set_event_all(const event_v2::event_t & e, std::chrono::milliseconds dt)
  10. {
  11. return std::thread([=]
  12. {
  13. std::this_thread::sleep_for(dt);
  14. e.notify_all();
  15. });
  16. }
  17. std::thread async_set_event_one(const event_v2::event_t& e, std::chrono::milliseconds dt)
  18. {
  19. return std::thread([=]
  20. {
  21. std::this_thread::sleep_for(dt);
  22. e.notify_one();
  23. });
  24. }
  25. future_t<> resumable_wait_event(const event_v2::event_t & e, int idx)
  26. {
  27. co_await e;
  28. std::cout << "[" << idx << "]event signal!" << std::endl;
  29. }
  30. void test_notify_all()
  31. {
  32. using namespace std::chrono;
  33. {
  34. event_v2::event_t evt;
  35. go resumable_wait_event(evt, 0);
  36. go resumable_wait_event(evt, 1);
  37. go resumable_wait_event(evt, 2);
  38. auto tt = async_set_event_all(evt, 100ms);
  39. this_scheduler()->run_until_notask();
  40. tt.join();
  41. }
  42. }
  43. //目前还没法测试在多线程调度下,是否线程安全
  44. void test_notify_one()
  45. {
  46. using namespace std::chrono;
  47. {
  48. event_v2::event_t evt;
  49. go resumable_wait_event(evt, 10);
  50. go resumable_wait_event(evt, 11);
  51. go resumable_wait_event(evt, 12);
  52. auto tt1 = async_set_event_one(evt, 100ms);
  53. auto tt2 = async_set_event_one(evt, 500ms);
  54. auto tt3 = async_set_event_one(evt, 800ms);
  55. this_scheduler()->run_until_notask();
  56. tt1.join();
  57. tt2.join();
  58. tt3.join();
  59. }
  60. }
  61. void resumable_main_event_v2()
  62. {
  63. test_notify_all();
  64. std::cout << std::endl;
  65. test_notify_one();
  66. std::cout << std::endl;
  67. }