基于C++ Coroutines提案 ‘Stackless Resumable Functions’编写的协程库
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

test_async_event_v2.cpp 1.7KB

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