1
0

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