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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. static 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.signal_all();
  15. });
  16. }
  17. static std::thread async_set_event_one(event_v2::event_t e, std::chrono::milliseconds dt)
  18. {
  19. return std::thread([=]
  20. {
  21. std::this_thread::sleep_for(dt);
  22. e.signal();
  23. });
  24. }
  25. static future_t<> resumable_wait_event(event_v2::event_t e, int idx)
  26. {
  27. if (co_await e)
  28. std::cout << "[" << idx << "]event signal!" << std::endl;
  29. else
  30. std::cout << "time out!" << std::endl;
  31. }
  32. static void test_notify_all()
  33. {
  34. using namespace std::chrono;
  35. {
  36. event_v2::event_t evt;
  37. go resumable_wait_event(evt, 0);
  38. go resumable_wait_event(evt, 1);
  39. go resumable_wait_event(evt, 2);
  40. auto tt = async_set_event_all(evt, 100ms);
  41. this_scheduler()->run_until_notask();
  42. tt.join();
  43. }
  44. }
  45. //目前还没法测试在多线程调度下,是否线程安全
  46. static void test_notify_one()
  47. {
  48. using namespace std::chrono;
  49. {
  50. event_v2::event_t evt;
  51. go resumable_wait_event(evt, 10);
  52. go resumable_wait_event(evt, 11);
  53. go resumable_wait_event(evt, 12);
  54. auto tt1 = async_set_event_one(evt, 100ms);
  55. auto tt2 = async_set_event_one(evt, 500ms);
  56. auto tt3 = async_set_event_one(evt, 800ms);
  57. this_scheduler()->run_until_notask();
  58. tt1.join();
  59. tt2.join();
  60. tt3.join();
  61. }
  62. }
  63. void resumable_main_event_v2()
  64. {
  65. test_notify_all();
  66. std::cout << std::endl;
  67. test_notify_one();
  68. std::cout << std::endl;
  69. }