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

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. 
  2. #include <chrono>
  3. #include <iostream>
  4. #include <string>
  5. #include <thread>
  6. #include "librf/librf.h"
  7. using namespace librf;
  8. future_t<> test_sleep_use_timer()
  9. {
  10. using namespace std::chrono;
  11. (void)sleep_for(100ms); //incorrect!!!
  12. co_await sleep_for(100ms);
  13. std::cout << "sleep_for 100ms." << std::endl;
  14. co_await 100ms;
  15. std::cout << "co_await 100ms." << std::endl;
  16. try
  17. {
  18. co_await sleep_until(system_clock::now() + 200ms);
  19. std::cout << "timer after 200ms." << std::endl;
  20. }
  21. catch (canceled_exception)
  22. {
  23. std::cout << "timer canceled." << std::endl;
  24. }
  25. }
  26. void test_wait_all_events_with_signal_by_sleep()
  27. {
  28. using namespace std::chrono;
  29. event_t evts[8];
  30. go[&]() -> future_t<>
  31. {
  32. auto result = co_await event_t::wait_all(evts);
  33. if (result)
  34. std::cout << "all event signal!" << std::endl;
  35. else
  36. std::cout << "time out!" << std::endl;
  37. };
  38. srand((int)time(nullptr));
  39. for (size_t i = 0; i < std::size(evts); ++i)
  40. {
  41. go[&, i]() -> future_t<>
  42. {
  43. co_await sleep_for(1ms * (500 + rand() % 1000));
  44. evts[i].signal();
  45. std::cout << "event[ " << i << " ] signal!" << std::endl;
  46. };
  47. }
  48. while (!this_scheduler()->empty())
  49. {
  50. this_scheduler()->run_one_batch();
  51. //std::cout << "press any key to continue." << std::endl;
  52. //_getch();
  53. }
  54. }
  55. void resumable_main_sleep()
  56. {
  57. go test_sleep_use_timer();
  58. this_scheduler()->run_until_notask();
  59. std::cout << std::endl;
  60. test_wait_all_events_with_signal_by_sleep();
  61. std::cout << std::endl;
  62. }
  63. #if LIBRF_TUTORIAL_STAND_ALONE
  64. int main()
  65. {
  66. resumable_main_sleep();
  67. return 0;
  68. }
  69. #endif