EventLoop.h 6.3 KB

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