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

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