EventLoop.h 6.5 KB

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