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