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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #include <chrono>
  2. #include <iostream>
  3. #include <string>
  4. #include <conio.h>
  5. #include <thread>
  6. #include <deque>
  7. #include <mutex>
  8. #include "librf.h"
  9. using namespace resumef;
  10. const size_t MAX_CHANNEL_QUEUE = 5; //0, 1, 5, 10, -1
  11. future_t<> test_channel_read(const channel_t<std::string> & c)
  12. {
  13. using namespace std::chrono;
  14. for (size_t i = 0; i < 10; ++i)
  15. {
  16. try
  17. {
  18. auto val = co_await c.read();
  19. //auto val = co_await c; //第二种从channel读出数据的方法。利用重载operator co_await(),而不是c是一个awaitable_t。
  20. std::cout << val << ":";
  21. #if _DEBUG
  22. for (auto val : c.debug_queue())
  23. std::cout << val << ",";
  24. #endif
  25. std::cout << std::endl;
  26. }
  27. catch (channel_exception e)
  28. {
  29. //MAX_CHANNEL_QUEUE=0,并且先读后写,会触发read_before_write异常
  30. std::cout << e.what() << std::endl;
  31. }
  32. co_await sleep_for(50ms);
  33. }
  34. }
  35. future_t<> test_channel_write(const channel_t<std::string> & c)
  36. {
  37. using namespace std::chrono;
  38. for (size_t i = 0; i < 10; ++i)
  39. {
  40. co_await c.write(std::to_string(i));
  41. //co_await (c << std::to_string(i)); //第二种写入数据到channel的方法。因为优先级关系,需要将'c << i'括起来
  42. std::cout << "<" << i << ">:";
  43. #if _DEBUG
  44. for (auto val : c.debug_queue())
  45. std::cout << val << ",";
  46. #endif
  47. std::cout << std::endl;
  48. }
  49. }
  50. void test_channel_read_first()
  51. {
  52. channel_t<std::string> c(MAX_CHANNEL_QUEUE);
  53. go test_channel_read(c);
  54. go test_channel_write(c);
  55. this_scheduler()->run_until_notask();
  56. }
  57. void test_channel_write_first()
  58. {
  59. channel_t<std::string> c(MAX_CHANNEL_QUEUE);
  60. go test_channel_write(c);
  61. go test_channel_read(c);
  62. this_scheduler()->run_until_notask();
  63. }
  64. void resumable_main_channel()
  65. {
  66. test_channel_read_first();
  67. std::cout << std::endl;
  68. test_channel_write_first();
  69. }