|
|
@@ -83,15 +83,18 @@ public:
|
|
|
}
|
|
|
|
|
|
// Timer interfaces: setTimer, killTimer, resetTimer
|
|
|
- TimerID setTimer(int timeout_ms, TimerCallback cb, int repeat = INFINITE) {
|
|
|
+ TimerID setTimer(int timeout_ms, TimerCallback cb, uint32_t repeat = INFINITE, TimerID timerID = INVALID_TIMER_ID) {
|
|
|
if (loop_ == NULL) return INVALID_TIMER_ID;
|
|
|
htimer_t* htimer = htimer_add(loop_, onTimer, timeout_ms, repeat);
|
|
|
+ if (timerID == INVALID_TIMER_ID) {
|
|
|
+ timerID = hevent_id(htimer);
|
|
|
+ } else {
|
|
|
+ hevent_set_id(htimer, timerID);
|
|
|
+ }
|
|
|
|
|
|
Timer timer(htimer, cb, repeat);
|
|
|
hevent_set_userdata(htimer, this);
|
|
|
|
|
|
- TimerID timerID = hevent_id(htimer);
|
|
|
-
|
|
|
mutex_.lock();
|
|
|
timers[timerID] = timer;
|
|
|
mutex_.unlock();
|
|
|
@@ -175,31 +178,25 @@ private:
|
|
|
EventLoop* loop = (EventLoop*)hevent_userdata(htimer);
|
|
|
|
|
|
TimerID timerID = hevent_id(htimer);
|
|
|
- TimerCallback cb = NULL;
|
|
|
+ Timer* timer = NULL;
|
|
|
|
|
|
loop->mutex_.lock();
|
|
|
auto iter = loop->timers.find(timerID);
|
|
|
if (iter != loop->timers.end()) {
|
|
|
- Timer& timer = iter->second;
|
|
|
- cb = timer.cb;
|
|
|
- --timer.repeat;
|
|
|
+ timer = &iter->second;
|
|
|
+ if (timer->repeat != INFINITE) --timer->repeat;
|
|
|
}
|
|
|
loop->mutex_.unlock();
|
|
|
|
|
|
- if (cb) cb(timerID);
|
|
|
-
|
|
|
- // NOTE: refind iterator, because iterator may be invalid
|
|
|
- // if the timer-related interface is called in the callback function above.
|
|
|
- loop->mutex_.lock();
|
|
|
- iter = loop->timers.find(timerID);
|
|
|
- if (iter != loop->timers.end()) {
|
|
|
- Timer& timer = iter->second;
|
|
|
- if (timer.repeat == 0) {
|
|
|
+ if (timer) {
|
|
|
+ if (timer->cb) timer->cb(timerID);
|
|
|
+ if (timer->repeat == 0) {
|
|
|
// htimer_t alloc and free by hloop, but timers[timerID] managed by EventLoop.
|
|
|
- loop->timers.erase(iter);
|
|
|
+ loop->mutex_.lock();
|
|
|
+ loop->timers.erase(timerID);
|
|
|
+ loop->mutex_.unlock();
|
|
|
}
|
|
|
}
|
|
|
- loop->mutex_.unlock();
|
|
|
}
|
|
|
|
|
|
static void onCustomEvent(hevent_t* hev) {
|
|
|
@@ -229,7 +226,7 @@ static inline EventLoop* tlsEventLoop() {
|
|
|
}
|
|
|
#define currentThreadEventLoop tlsEventLoop()
|
|
|
|
|
|
-static inline TimerID setTimer(int timeout_ms, TimerCallback cb, int repeat = INFINITE) {
|
|
|
+static inline TimerID setTimer(int timeout_ms, TimerCallback cb, uint32_t repeat = INFINITE) {
|
|
|
EventLoop* loop = tlsEventLoop();
|
|
|
assert(loop != NULL);
|
|
|
if (loop == NULL) return INVALID_TIMER_ID;
|