EventLoop.h 6.2 KB

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