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.

common.h 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*********************************************************
  2. File Name: common.h
  3. Author: Abby Cin
  4. Mail: abbytsing@gmail.com
  5. Created Time: Fri 06 Mar 2020 08:22:37 PM CST
  6. **********************************************************/
  7. #ifndef WS_COMMON_H
  8. #define WS_COMMON_H
  9. #include <thread>
  10. #include <vector>
  11. #include "asio.hpp"
  12. class IoContextPool
  13. {
  14. public:
  15. IoContextPool(int n = std::thread::hardware_concurrency())
  16. {
  17. for(int i = 0; i < n; ++i)
  18. {
  19. auto ctx = new asio::io_context{};
  20. work_.emplace_back(new asio::io_context::work{*ctx});
  21. ctx_.emplace_back(ctx);
  22. }
  23. }
  24. ~IoContextPool() { stop(); }
  25. asio::io_context& get_context()
  26. {
  27. if(cur_ == ctx_.size())
  28. {
  29. cur_ = 0;
  30. }
  31. return *ctx_[cur_++];
  32. }
  33. void run()
  34. {
  35. for(size_t i = 0; i < ctx_.size(); ++i)
  36. {
  37. worker_.emplace_back(new std::thread{[](std::shared_ptr<asio::io_context> ioc) { ioc->run(); }, ctx_[i]});
  38. }
  39. for(auto& t: worker_)
  40. {
  41. try
  42. {
  43. t->join();
  44. }
  45. catch(...)
  46. {
  47. }
  48. }
  49. }
  50. void stop()
  51. {
  52. for(auto& c: ctx_)
  53. {
  54. c->stop();
  55. }
  56. }
  57. private:
  58. size_t cur_{0};
  59. std::vector<std::shared_ptr<asio::io_context>> ctx_{};
  60. std::vector<std::shared_ptr<asio::io_context::work>> work_{}; // work_ should destroy before ctx_
  61. std::vector<std::shared_ptr<std::thread>> worker_{};
  62. };
  63. #endif // WS_COMMON_H