1
0

EventLoop.h 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. #ifndef HV_EVENT_LOOP_HPP_
  2. #define HV_EVENT_LOOP_HPP_
  3. #include <functional>
  4. #include <queue>
  5. #include <map>
  6. #include <mutex>
  7. #include "hloop.h"
  8. #include "hthread.h"
  9. #include "Status.h"
  10. #include "Event.h"
  11. #include "ThreadLocalStorage.h"
  12. namespace hv {
  13. class EventLoop : public Status {
  14. public:
  15. typedef std::function<void()> Functor;
  16. // New an EventLoop using an existing hloop_t object,
  17. // so we can embed an EventLoop object into the old application based on hloop.
  18. // NOTE: Be careful to deal with destroy of hloop_t.
  19. EventLoop(hloop_t* loop = NULL) {
  20. setStatus(kInitializing);
  21. if (loop) {
  22. loop_ = loop;
  23. is_loop_owner = false;
  24. } else {
  25. loop_ = hloop_new(HLOOP_FLAG_AUTO_FREE);
  26. is_loop_owner = true;
  27. }
  28. connectionNum = 0;
  29. nextTimerID = 0;
  30. setStatus(kInitialized);
  31. }
  32. ~EventLoop() {
  33. stop();
  34. }
  35. hloop_t* loop() {
  36. return loop_;
  37. }
  38. // @brief Run loop forever
  39. void run() {
  40. if (loop_ == NULL) return;
  41. if (status() == kRunning) return;
  42. ThreadLocalStorage::set(ThreadLocalStorage::EVENT_LOOP, this);
  43. setStatus(kRunning);
  44. hloop_run(loop_);
  45. setStatus(kStopped);
  46. }
  47. // stop thread-safe
  48. void stop() {
  49. if (loop_ == NULL) return;
  50. if (status() < kRunning) {
  51. if (is_loop_owner) {
  52. hloop_free(&loop_);
  53. }
  54. loop_ = NULL;
  55. return;
  56. }
  57. setStatus(kStopping);
  58. hloop_stop(loop_);
  59. loop_ = NULL;
  60. }
  61. void pause() {
  62. if (loop_ == NULL) return;
  63. if (isRunning()) {
  64. hloop_pause(loop_);
  65. setStatus(kPause);
  66. }
  67. }
  68. void resume() {
  69. if (loop_ == NULL) return;
  70. if (isPause()) {
  71. hloop_resume(loop_);
  72. setStatus(kRunning);
  73. }
  74. }
  75. // Timer interfaces: setTimer, killTimer, resetTimer
  76. TimerID setTimer(int timeout_ms, TimerCallback cb, uint32_t repeat = INFINITE, TimerID timerID = INVALID_TIMER_ID) {
  77. if (loop_ == NULL) return INVALID_TIMER_ID;
  78. assertInLoopThread();
  79. htimer_t* htimer = htimer_add(loop_, onTimer, timeout_ms, repeat);
  80. assert(htimer != NULL);
  81. if (timerID == INVALID_TIMER_ID) {
  82. timerID = generateTimerID();
  83. }
  84. hevent_set_id(htimer, timerID);
  85. hevent_set_userdata(htimer, this);
  86. timers[timerID] = std::make_shared<Timer>(htimer, cb, repeat);
  87. return timerID;
  88. }
  89. // setTimerInLoop thread-safe
  90. TimerID setTimerInLoop(int timeout_ms, TimerCallback cb, uint32_t repeat = INFINITE, TimerID timerID = INVALID_TIMER_ID) {
  91. if (timerID == INVALID_TIMER_ID) {
  92. timerID = generateTimerID();
  93. }
  94. runInLoop(std::bind(&EventLoop::setTimer, this, timeout_ms, cb, repeat, timerID));
  95. return timerID;
  96. }
  97. // alias javascript setTimeout, setInterval
  98. // setTimeout thread-safe
  99. TimerID setTimeout(int timeout_ms, TimerCallback cb) {
  100. return setTimerInLoop(timeout_ms, cb, 1);
  101. }
  102. // setInterval thread-safe
  103. TimerID setInterval(int interval_ms, TimerCallback cb) {
  104. return setTimerInLoop(interval_ms, cb, INFINITE);
  105. }
  106. // killTimer thread-safe
  107. void killTimer(TimerID timerID) {
  108. runInLoop([timerID, this](){
  109. auto iter = timers.find(timerID);
  110. if (iter != timers.end()) {
  111. htimer_del(iter->second->timer);
  112. timers.erase(iter);
  113. }
  114. });
  115. }
  116. // resetTimer thread-safe
  117. void resetTimer(TimerID timerID, int timeout_ms = 0) {
  118. runInLoop([timerID, timeout_ms, this](){
  119. auto iter = timers.find(timerID);
  120. if (iter != timers.end()) {
  121. htimer_reset(iter->second->timer, timeout_ms);
  122. if (iter->second->repeat == 0) {
  123. iter->second->repeat = 1;
  124. }
  125. }
  126. });
  127. }
  128. long tid() {
  129. if (loop_ == NULL) return hv_gettid();
  130. return hloop_tid(loop_);
  131. }
  132. bool isInLoopThread() {
  133. if (loop_ == NULL) return false;
  134. return hv_gettid() == hloop_tid(loop_);
  135. }
  136. void assertInLoopThread() {
  137. assert(isInLoopThread());
  138. }
  139. void runInLoop(Functor fn) {
  140. if (isRunning() && isInLoopThread()) {
  141. if (fn) fn();
  142. } else {
  143. queueInLoop(std::move(fn));
  144. }
  145. }
  146. void queueInLoop(Functor fn) {
  147. postEvent([fn](Event* ev) {
  148. if (fn) fn();
  149. });
  150. }
  151. void postEvent(EventCallback cb) {
  152. if (loop_ == NULL) return;
  153. EventPtr ev = std::make_shared<Event>(cb);
  154. hevent_set_userdata(&ev->event, this);
  155. ev->event.cb = onCustomEvent;
  156. mutex_.lock();
  157. customEvents.push(ev);
  158. mutex_.unlock();
  159. hloop_post_event(loop_, &ev->event);
  160. }
  161. private:
  162. TimerID generateTimerID() {
  163. return (((TimerID)tid() & 0xFFFFFFFF) << 32) | ++nextTimerID;
  164. }
  165. static void onTimer(htimer_t* htimer) {
  166. EventLoop* loop = (EventLoop*)hevent_userdata(htimer);
  167. TimerID timerID = hevent_id(htimer);
  168. TimerPtr timer = NULL;
  169. auto iter = loop->timers.find(timerID);
  170. if (iter != loop->timers.end()) {
  171. timer = iter->second;
  172. if (timer->repeat != INFINITE) --timer->repeat;
  173. }
  174. if (timer) {
  175. if (timer->cb) timer->cb(timerID);
  176. if (timer->repeat == 0) {
  177. // htimer_t alloc and free by hloop, but timers[timerID] managed by EventLoop.
  178. loop->timers.erase(timerID);
  179. }
  180. }
  181. }
  182. static void onCustomEvent(hevent_t* hev) {
  183. EventLoop* loop = (EventLoop*)hevent_userdata(hev);
  184. loop->mutex_.lock();
  185. EventPtr ev = loop->customEvents.front();
  186. loop->customEvents.pop();
  187. loop->mutex_.unlock();
  188. if (ev && ev->cb) ev->cb(ev.get());
  189. }
  190. public:
  191. std::atomic<uint32_t> connectionNum; // for LB_LeastConnections
  192. private:
  193. hloop_t* loop_;
  194. bool is_loop_owner;
  195. std::mutex mutex_;
  196. std::queue<EventPtr> customEvents; // GUAREDE_BY(mutex_)
  197. std::map<TimerID, TimerPtr> timers;
  198. std::atomic<TimerID> nextTimerID;
  199. };
  200. typedef std::shared_ptr<EventLoop> EventLoopPtr;
  201. // ThreadLocalStorage
  202. static inline EventLoop* tlsEventLoop() {
  203. return (EventLoop*)ThreadLocalStorage::get(ThreadLocalStorage::EVENT_LOOP);
  204. }
  205. #define currentThreadEventLoop ::hv::tlsEventLoop()
  206. static inline TimerID setTimer(int timeout_ms, TimerCallback cb, uint32_t repeat = INFINITE) {
  207. EventLoop* loop = tlsEventLoop();
  208. assert(loop != NULL);
  209. if (loop == NULL) return INVALID_TIMER_ID;
  210. return loop->setTimer(timeout_ms, cb, repeat);
  211. }
  212. static inline void killTimer(TimerID timerID) {
  213. EventLoop* loop = tlsEventLoop();
  214. assert(loop != NULL);
  215. if (loop == NULL) return;
  216. loop->killTimer(timerID);
  217. }
  218. static inline void resetTimer(TimerID timerID, int timeout_ms) {
  219. EventLoop* loop = tlsEventLoop();
  220. assert(loop != NULL);
  221. if (loop == NULL) return;
  222. loop->resetTimer(timerID, timeout_ms);
  223. }
  224. static inline TimerID setTimeout(int timeout_ms, TimerCallback cb) {
  225. return setTimer(timeout_ms, cb, 1);
  226. }
  227. static inline TimerID setInterval(int interval_ms, TimerCallback cb) {
  228. return setTimer(interval_ms, cb, INFINITE);
  229. }
  230. }
  231. #endif // HV_EVENT_LOOP_HPP_