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