基于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_mult_thread.cpp 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. //验证channel是否线程安全
  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. using namespace std::chrono;
  12. static std::mutex cout_mutex;
  13. #define OUTPUT_DEBUG 0
  14. future_vt test_channel_consumer(const channel_t<std::string> & c, size_t cnt)
  15. {
  16. for (size_t i = 0; i < cnt; ++i)
  17. {
  18. try
  19. {
  20. auto val = co_await c.read();
  21. #if OUTPUT_DEBUG
  22. {
  23. scoped_lock<std::mutex> __lock(cout_mutex);
  24. std::cout << "R " << val << "@" << std::this_thread::get_id() << std::endl;
  25. }
  26. #endif
  27. }
  28. catch (channel_exception e)
  29. {
  30. //MAX_CHANNEL_QUEUE=0,并且先读后写,会触发read_before_write异常
  31. scoped_lock<std::mutex> __lock(cout_mutex);
  32. std::cout << e.what() << std::endl;
  33. }
  34. #if OUTPUT_DEBUG
  35. co_await sleep_for(50ms);
  36. #endif
  37. }
  38. }
  39. future_vt test_channel_producer(const channel_t<std::string> & c, size_t cnt)
  40. {
  41. for (size_t i = 0; i < cnt; ++i)
  42. {
  43. co_await c.write(std::to_string(i));
  44. #if OUTPUT_DEBUG
  45. {
  46. scoped_lock<std::mutex> __lock(cout_mutex);
  47. std::cout << "W " << i << "@" << std::this_thread::get_id() << std::endl;
  48. }
  49. #endif
  50. }
  51. }
  52. const size_t N = 8;
  53. const size_t BATCH = 1000000;
  54. const size_t MAX_CHANNEL_QUEUE = N + 1; //0, 1, 5, 10, -1
  55. void resumable_main_channel_mult_thread()
  56. {
  57. channel_t<std::string> c(MAX_CHANNEL_QUEUE);
  58. std::thread write_th([&]
  59. {
  60. //local_scheduler my_scheduler; //2017/11/27日,仍然存在BUG。真多线程下调度,存在有协程无法被调度完成的BUG
  61. go test_channel_producer(c, BATCH * N);
  62. this_scheduler()->run_until_notask();
  63. std::cout << "Write OK\r\n";
  64. });
  65. //std::this_thread::sleep_for(100ms);
  66. std::thread read_th[N];
  67. for (size_t i = 0; i < N; ++i)
  68. {
  69. read_th[i] = std::thread([&]
  70. {
  71. //local_scheduler my_scheduler; //2017/11/27日,仍然存在BUG。真多线程下调度,存在有协程无法被调度完成的BUG
  72. go test_channel_consumer(c, BATCH);
  73. this_scheduler()->run_until_notask();
  74. std::cout << "Read OK\r\n";
  75. });
  76. }
  77. for(auto & th : read_th)
  78. th.join();
  79. write_th.join();
  80. std::cout << "OK" << std::endl;
  81. _getch();
  82. }