EventPoller.h 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. /*
  2. * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  3. *
  4. * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
  5. *
  6. * Use of this source code is governed by MIT license that can be found in the
  7. * LICENSE file in the root of the source tree. All contributing project authors
  8. * may be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef EventPoller_h
  11. #define EventPoller_h
  12. #include <mutex>
  13. #include <thread>
  14. #include <string>
  15. #include <functional>
  16. #include <memory>
  17. #include <unordered_map>
  18. #include "PipeWrap.h"
  19. #include "Util/logger.h"
  20. #include "Util/List.h"
  21. #include "Thread/TaskExecutor.h"
  22. #include "Thread/ThreadPool.h"
  23. #include "Network/Buffer.h"
  24. #if defined(__linux__) || defined(__linux)
  25. #define HAS_EPOLL
  26. #endif //__linux__
  27. namespace toolkit {
  28. class EventPoller : public TaskExecutor, public AnyStorage, public std::enable_shared_from_this<EventPoller> {
  29. public:
  30. friend class TaskExecutorGetterImp;
  31. using Ptr = std::shared_ptr<EventPoller>;
  32. using PollEventCB = std::function<void(int event)>;
  33. using PollDelCB = std::function<void(bool success)>;
  34. using DelayTask = TaskCancelableImp<uint64_t(void)>;
  35. typedef enum {
  36. Event_Read = 1 << 0, //读事件
  37. Event_Write = 1 << 1, //写事件
  38. Event_Error = 1 << 2, //错误事件
  39. Event_LT = 1 << 3,//水平触发
  40. } Poll_Event;
  41. ~EventPoller();
  42. /**
  43. * 获取EventPollerPool单例中的第一个EventPoller实例,
  44. * 保留该接口是为了兼容老代码
  45. * @return 单例
  46. */
  47. static EventPoller &Instance();
  48. /**
  49. * 添加事件监听
  50. * @param fd 监听的文件描述符
  51. * @param event 事件类型,例如 Event_Read | Event_Write
  52. * @param cb 事件回调functional
  53. * @return -1:失败,0:成功
  54. */
  55. int addEvent(int fd, int event, PollEventCB cb);
  56. /**
  57. * 删除事件监听
  58. * @param fd 监听的文件描述符
  59. * @param cb 删除成功回调functional
  60. * @return -1:失败,0:成功
  61. */
  62. int delEvent(int fd, PollDelCB cb = nullptr);
  63. /**
  64. * 修改监听事件类型
  65. * @param fd 监听的文件描述符
  66. * @param event 事件类型,例如 Event_Read | Event_Write
  67. * @return -1:失败,0:成功
  68. */
  69. int modifyEvent(int fd, int event);
  70. /**
  71. * 异步执行任务
  72. * @param task 任务
  73. * @param may_sync 如果调用该函数的线程就是本对象的轮询线程,那么may_sync为true时就是同步执行任务
  74. * @return 是否成功,一定会返回true
  75. */
  76. Task::Ptr async(TaskIn task, bool may_sync = true) override;
  77. /**
  78. * 同async方法,不过是把任务打入任务列队头,这样任务优先级最高
  79. * @param task 任务
  80. * @param may_sync 如果调用该函数的线程就是本对象的轮询线程,那么may_sync为true时就是同步执行任务
  81. * @return 是否成功,一定会返回true
  82. */
  83. Task::Ptr async_first(TaskIn task, bool may_sync = true) override;
  84. /**
  85. * 判断执行该接口的线程是否为本对象的轮询线程
  86. * @return 是否为本对象的轮询线程
  87. */
  88. bool isCurrentThread();
  89. /**
  90. * 延时执行某个任务
  91. * @param delay_ms 延时毫秒数
  92. * @param task 任务,返回值为0时代表不再重复任务,否则为下次执行延时,如果任务中抛异常,那么默认不重复任务
  93. * @return 可取消的任务标签
  94. */
  95. DelayTask::Ptr doDelayTask(uint64_t delay_ms, std::function<uint64_t()> task);
  96. /**
  97. * 获取当前线程关联的Poller实例
  98. */
  99. static EventPoller::Ptr getCurrentPoller();
  100. /**
  101. * 获取当前线程下所有socket共享的读缓存
  102. */
  103. BufferRaw::Ptr getSharedBuffer();
  104. /**
  105. * 获取poller线程id
  106. */
  107. const std::thread::id& getThreadId() const;
  108. /**
  109. * 获取线程名
  110. */
  111. const std::string& getThreadName() const;
  112. private:
  113. /**
  114. * 本对象只允许在EventPollerPool中构造
  115. */
  116. EventPoller(std::string name, ThreadPool::Priority priority = ThreadPool::PRIORITY_HIGHEST);
  117. /**
  118. * 执行事件轮询
  119. * @param blocked 是否用执行该接口的线程执行轮询
  120. * @param ref_self 是记录本对象到thread local变量
  121. */
  122. void runLoop(bool blocked, bool ref_self);
  123. /**
  124. * 内部管道事件,用于唤醒轮询线程用
  125. */
  126. void onPipeEvent();
  127. /**
  128. * 切换线程并执行任务
  129. * @param task
  130. * @param may_sync
  131. * @param first
  132. * @return 可取消的任务本体,如果已经同步执行,则返回nullptr
  133. */
  134. Task::Ptr async_l(TaskIn task, bool may_sync = true, bool first = false);
  135. /**
  136. * 阻塞当前线程,等待轮询线程退出;
  137. * 在执行shutdown接口时本函数会退出
  138. */
  139. void wait();
  140. /**
  141. * 结束事件轮询
  142. * 需要指出的是,一旦结束就不能再次恢复轮询线程
  143. */
  144. void shutdown();
  145. /**
  146. * 刷新延时任务
  147. */
  148. uint64_t flushDelayTask(uint64_t now);
  149. /**
  150. * 获取select或epoll休眠时间
  151. */
  152. uint64_t getMinDelay();
  153. /**
  154. * 添加管道监听事件
  155. */
  156. void addEventPipe();
  157. private:
  158. class ExitException : public std::exception {};
  159. private:
  160. //标记loop线程是否退出
  161. bool _exit_flag;
  162. //线程名
  163. std::string _name;
  164. //当前线程下,所有socket共享的读缓存
  165. std::weak_ptr<BufferRaw> _shared_buffer;
  166. //线程优先级
  167. ThreadPool::Priority _priority;
  168. //正在运行事件循环时该锁处于被锁定状态
  169. std::mutex _mtx_running;
  170. //执行事件循环的线程
  171. std::thread *_loop_thread = nullptr;
  172. //事件循环的线程id
  173. std::thread::id _loop_thread_id;
  174. //通知事件循环的线程已启动
  175. semaphore _sem_run_started;
  176. //内部事件管道
  177. PipeWrap _pipe;
  178. //从其他线程切换过来的任务
  179. std::mutex _mtx_task;
  180. List<Task::Ptr> _list_task;
  181. //保持日志可用
  182. Logger::Ptr _logger;
  183. #if defined(HAS_EPOLL)
  184. //epoll相关
  185. int _epoll_fd = -1;
  186. unordered_map<int, std::shared_ptr<PollEventCB> > _event_map;
  187. #else
  188. //select相关
  189. struct Poll_Record {
  190. using Ptr = std::shared_ptr<Poll_Record>;
  191. int event;
  192. int attach;
  193. PollEventCB call_back;
  194. };
  195. unordered_map<int, Poll_Record::Ptr> _event_map;
  196. #endif //HAS_EPOLL
  197. //定时器相关
  198. std::multimap<uint64_t, DelayTask::Ptr> _delay_task_map;
  199. };
  200. class EventPollerPool : public std::enable_shared_from_this<EventPollerPool>, public TaskExecutorGetterImp {
  201. public:
  202. using Ptr = std::shared_ptr<EventPollerPool>;
  203. static const std::string kOnStarted;
  204. ~EventPollerPool() = default;
  205. /**
  206. * 获取单例
  207. * @return
  208. */
  209. static EventPollerPool &Instance();
  210. /**
  211. * 设置EventPoller个数,在EventPollerPool单例创建前有效
  212. * 在不调用此方法的情况下,默认创建thread::hardware_concurrency()个EventPoller实例
  213. * @param size EventPoller个数,如果为0则为thread::hardware_concurrency()
  214. */
  215. static void setPoolSize(size_t size = 0);
  216. /**
  217. * 内部创建线程是否设置cpu亲和性,默认设置cpu亲和性
  218. */
  219. static void enableCpuAffinity(bool enable);
  220. /**
  221. * 获取第一个实例
  222. * @return
  223. */
  224. EventPoller::Ptr getFirstPoller();
  225. /**
  226. * 根据负载情况获取轻负载的实例
  227. * 如果优先返回当前线程,那么会返回当前线程
  228. * 返回当前线程的目的是为了提高线程安全性
  229. * @param prefer_current_thread 是否优先获取当前线程
  230. */
  231. EventPoller::Ptr getPoller(bool prefer_current_thread = true);
  232. /**
  233. * 设置 getPoller() 是否优先返回当前线程
  234. * 在批量创建Socket对象时,如果优先返回当前线程,
  235. * 那么将导致负载不够均衡,所以可以暂时关闭然后再开启
  236. * @param flag 是否优先返回当前线程
  237. */
  238. void preferCurrentThread(bool flag = true);
  239. private:
  240. EventPollerPool();
  241. private:
  242. bool _prefer_current_thread = true;
  243. };
  244. } // namespace toolkit
  245. #endif /* EventPoller_h */