1
0

EventLoop.h 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. setStatus(kInitialized);
  30. }
  31. ~EventLoop() {
  32. stop();
  33. }
  34. hloop_t* loop() {
  35. return loop_;
  36. }
  37. // @brief Run loop forever
  38. void run() {
  39. if (loop_ == NULL) return;
  40. if (status() == kRunning) return;
  41. ThreadLocalStorage::set(ThreadLocalStorage::EVENT_LOOP, this);
  42. setStatus(kRunning);
  43. hloop_run(loop_);
  44. setStatus(kStopped);
  45. }
  46. // stop thread-safe
  47. void stop() {
  48. if (loop_ == NULL) return;
  49. if (status() < kRunning) {
  50. if (is_loop_owner) {
  51. hloop_free(&loop_);
  52. }
  53. loop_ = NULL;
  54. return;
  55. }
  56. setStatus(kStopping);
  57. hloop_stop(loop_);
  58. loop_ = NULL;
  59. }
  60. void pause() {
  61. if (loop_ == NULL) return;
  62. if (isRunning()) {
  63. hloop_pause(loop_);
  64. setStatus(kPause);
  65. }
  66. }
  67. void resume() {
  68. if (loop_ == NULL) return;
  69. if (isPause()) {
  70. hloop_resume(loop_);
  71. setStatus(kRunning);
  72. }
  73. }
  74. // Timer interfaces: setTimer, killTimer, resetTimer
  75. TimerID setTimer(int timeout_ms, TimerCallback cb, uint32_t repeat = INFINITE, TimerID timerID = INVALID_TIMER_ID) {
  76. if (loop_ == NULL) return INVALID_TIMER_ID;
  77. htimer_t* htimer = htimer_add(loop_, onTimer, timeout_ms, repeat);
  78. if (timerID == INVALID_TIMER_ID) {
  79. timerID = hevent_id(htimer);
  80. } else {
  81. hevent_set_id(htimer, timerID);
  82. }
  83. TimerPtr timer = std::make_shared<Timer>(htimer, cb, repeat);
  84. hevent_set_userdata(htimer, this);
  85. mutex_.lock();
  86. timers[timerID] = std::move(timer);
  87. mutex_.unlock();
  88. return timerID;
  89. }
  90. // alias javascript setTimeout, setInterval
  91. TimerID setTimeout(int timeout_ms, TimerCallback cb) {
  92. return setTimer(timeout_ms, cb, 1);
  93. }
  94. TimerID setInterval(int interval_ms, TimerCallback cb) {
  95. return setTimer(interval_ms, cb, INFINITE);
  96. }
  97. void killTimer(TimerID timerID) {
  98. std::lock_guard<std::mutex> locker(mutex_);
  99. auto iter = timers.find(timerID);
  100. if (iter != timers.end()) {
  101. htimer_del(iter->second->timer);
  102. timers.erase(iter);
  103. }
  104. }
  105. void resetTimer(TimerID timerID, int timeout_ms = 0) {
  106. std::lock_guard<std::mutex> locker(mutex_);
  107. auto iter = timers.find(timerID);
  108. if (iter != timers.end()) {
  109. htimer_reset(iter->second->timer, timeout_ms);
  110. if (iter->second->repeat == 0) {
  111. iter->second->repeat = 1;
  112. }
  113. }
  114. }
  115. long tid() {
  116. if (loop_ == NULL) return hv_gettid();
  117. return hloop_tid(loop_);
  118. }
  119. bool isInLoopThread() {
  120. if (loop_ == NULL) return false;
  121. return hv_gettid() == hloop_tid(loop_);
  122. }
  123. void assertInLoopThread() {
  124. assert(isInLoopThread());
  125. }
  126. void runInLoop(Functor fn) {
  127. if (isRunning() && isInLoopThread()) {
  128. if (fn) fn();
  129. } else {
  130. queueInLoop(std::move(fn));
  131. }
  132. }
  133. void queueInLoop(Functor fn) {
  134. postEvent([fn](Event* ev) {
  135. if (fn) fn();
  136. });
  137. }
  138. void postEvent(EventCallback cb) {
  139. if (loop_ == NULL) return;
  140. EventPtr ev(new Event(cb));
  141. hevent_set_userdata(&ev->event, this);
  142. ev->event.cb = onCustomEvent;
  143. mutex_.lock();
  144. customEvents.push(ev);
  145. mutex_.unlock();
  146. hloop_post_event(loop_, &ev->event);
  147. }
  148. private:
  149. static void onTimer(htimer_t* htimer) {
  150. EventLoop* loop = (EventLoop*)hevent_userdata(htimer);
  151. TimerID timerID = hevent_id(htimer);
  152. TimerPtr timer = NULL;
  153. loop->mutex_.lock();
  154. auto iter = loop->timers.find(timerID);
  155. if (iter != loop->timers.end()) {
  156. timer = iter->second;
  157. if (timer->repeat != INFINITE) --timer->repeat;
  158. }
  159. loop->mutex_.unlock();
  160. if (timer) {
  161. if (timer->cb) timer->cb(timerID);
  162. if (timer->repeat == 0) {
  163. // htimer_t alloc and free by hloop, but timers[timerID] managed by EventLoop.
  164. loop->mutex_.lock();
  165. loop->timers.erase(timerID);
  166. loop->mutex_.unlock();
  167. }
  168. }
  169. }
  170. static void onCustomEvent(hevent_t* hev) {
  171. EventLoop* loop = (EventLoop*)hevent_userdata(hev);
  172. loop->mutex_.lock();
  173. EventPtr ev = loop->customEvents.front();
  174. loop->customEvents.pop();
  175. loop->mutex_.unlock();
  176. if (ev && ev->cb) ev->cb(ev.get());
  177. }
  178. public:
  179. std::atomic<uint32_t> connectionNum; // for LB_LeastConnections
  180. private:
  181. hloop_t* loop_;
  182. bool is_loop_owner;
  183. std::mutex mutex_;
  184. std::queue<EventPtr> customEvents; // GUAREDE_BY(mutex_)
  185. std::map<TimerID, TimerPtr> timers; // GUAREDE_BY(mutex_)
  186. };
  187. typedef std::shared_ptr<EventLoop> EventLoopPtr;
  188. // ThreadLocalStorage
  189. static inline EventLoop* tlsEventLoop() {
  190. return (EventLoop*)ThreadLocalStorage::get(ThreadLocalStorage::EVENT_LOOP);
  191. }
  192. #define currentThreadEventLoop tlsEventLoop()
  193. static inline TimerID setTimer(int timeout_ms, TimerCallback cb, uint32_t repeat = INFINITE) {
  194. EventLoop* loop = tlsEventLoop();
  195. assert(loop != NULL);
  196. if (loop == NULL) return INVALID_TIMER_ID;
  197. return loop->setTimer(timeout_ms, cb, repeat);
  198. }
  199. static inline void killTimer(TimerID timerID) {
  200. EventLoop* loop = tlsEventLoop();
  201. assert(loop != NULL);
  202. if (loop == NULL) return;
  203. loop->killTimer(timerID);
  204. }
  205. static inline void resetTimer(TimerID timerID, int timeout_ms) {
  206. EventLoop* loop = tlsEventLoop();
  207. assert(loop != NULL);
  208. if (loop == NULL) return;
  209. loop->resetTimer(timerID, timeout_ms);
  210. }
  211. static inline TimerID setTimeout(int timeout_ms, TimerCallback cb) {
  212. return setTimer(timeout_ms, cb, 1);
  213. }
  214. static inline TimerID setInterval(int interval_ms, TimerCallback cb) {
  215. return setTimer(interval_ms, cb, INFINITE);
  216. }
  217. }
  218. #endif // HV_EVENT_LOOP_HPP_