EventLoop.h 6.7 KB

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