基于C++ Coroutines提案 ‘Stackless Resumable Functions’编写的协程库
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

test_async_sleep.cpp 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include <chrono>
  2. #include <iostream>
  3. #include <string>
  4. #include <thread>
  5. #include "librf.h"
  6. using namespace resumef;
  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 (timer_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. if (co_await event_t::wait_all(evts))
  32. std::cout << "all event signal!" << std::endl;
  33. else
  34. std::cout << "time out!" << std::endl;
  35. };
  36. srand((int)time(nullptr));
  37. for (size_t i = 0; i < _countof(evts); ++i)
  38. {
  39. go[&, i]() -> future_t<>
  40. {
  41. co_await sleep_for(1ms * (500 + rand() % 1000));
  42. evts[i].signal();
  43. std::cout << "event[ " << i << " ] signal!" << std::endl;
  44. };
  45. }
  46. while (!this_scheduler()->empty())
  47. {
  48. this_scheduler()->run_one_batch();
  49. //std::cout << "press any key to continue." << std::endl;
  50. //_getch();
  51. }
  52. }
  53. void resumable_main_sleep()
  54. {
  55. go test_sleep_use_timer();
  56. this_scheduler()->run_until_notask();
  57. std::cout << std::endl;
  58. test_wait_all_events_with_signal_by_sleep();
  59. std::cout << std::endl;
  60. }