基于C++ Coroutines提案 ‘Stackless Resumable Functions’编写的协程库
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

test_async_channel.cpp 1.9KB

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