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.

context.h 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. /***********************************************
  2. File Name: context.h
  3. Author: Abby Cin
  4. Mail: abbytsing@gmail.com
  5. Created Time: 10/24/20 2:43 PM
  6. ***********************************************/
  7. #ifndef _CONET_CONTEXT_H_
  8. #define _CONET_CONTEXT_H_
  9. class peer;
  10. class acceptor;
  11. class context
  12. {
  13. public:
  14. context() : efd_{-1}, stop_{true}, revs_{1}, conn_{} { efd_ = ::epoll_create1(EPOLL_CLOEXEC); }
  15. ~context() { cleanup(); }
  16. int run()
  17. {
  18. stop_ = false;
  19. while(!stop_)
  20. {
  21. errno = 0;
  22. int res = ::epoll_wait(efd_, revs_.data(), revs_.size(), -1);
  23. if(res < 0)
  24. {
  25. return res;
  26. }
  27. for(int i = 0; i < res; ++i)
  28. {
  29. if((revs_[i].events & EPOLLIN) || (revs_[i].events & EPOLLPRI) || (revs_[i].events & EPOLLHUP) ||
  30. (revs_[i].events & EPOLLERR))
  31. {
  32. auto co = conn_.find(revs_[i].data.fd);
  33. if(co != conn_.end())
  34. {
  35. co->second.resume();
  36. }
  37. }
  38. }
  39. }
  40. return 0;
  41. }
  42. void stop()
  43. {
  44. stop_ = true;
  45. cleanup();
  46. }
  47. bool running() { return !stop_; }
  48. private:
  49. int efd_;
  50. std::atomic_bool stop_;
  51. std::vector<epoll_event> revs_;
  52. std::map<int, handle_t> conn_;
  53. friend peer;
  54. friend acceptor;
  55. void cleanup()
  56. {
  57. for(auto& [_, v]: conn_)
  58. {
  59. v.destroy();
  60. }
  61. conn_.clear();
  62. }
  63. int push(int fd, handle_t co)
  64. {
  65. if(!conn_.contains(fd))
  66. {
  67. epoll_event ev{};
  68. ev.data.fd = fd;
  69. ev.events = EPOLLIN;
  70. int r = ::epoll_ctl(efd_, EPOLL_CTL_ADD, fd, &ev);
  71. if(r < 0)
  72. {
  73. return r;
  74. }
  75. }
  76. if(conn_.size() + 1 == revs_.size())
  77. {
  78. revs_.resize(revs_.size() * 2);
  79. }
  80. conn_[fd] = co;
  81. return 0;
  82. }
  83. int pop(int fd)
  84. {
  85. debug("remove from loop:", fd);
  86. auto c = conn_.find(fd);
  87. if(c != conn_.end())
  88. {
  89. c->second = nullptr;
  90. conn_.erase(c);
  91. }
  92. epoll_event ev{};
  93. ev.events = EPOLLIN;
  94. ev.data.fd = fd;
  95. return ::epoll_ctl(efd_, EPOLL_CTL_DEL, fd, &ev);
  96. }
  97. };
  98. #endif //_CONET_CONTEXT_H_