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

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