| 140 | } |
| 141 | |
| 142 | void Timers::threadLoop() { |
| 143 | std::unique_lock<std::mutex> lk(mutex); |
| 144 | while (!stopped) { |
| 145 | if (!sortedTimers_.empty()) { |
| 146 | auto timer = sortedTimers_.at(0); |
| 147 | if (deletedTimers_.find(timer->id) != deletedTimers_.end()) { |
| 148 | sortedTimers_.erase(sortedTimers_.begin()); |
| 149 | deletedTimers_.erase(timer->id); |
| 150 | continue; |
| 151 | } |
| 152 | auto now = now_ms(); |
| 153 | // timer has reached its time, fire it and keep going |
| 154 | if (timer->dueTime <= now) { |
| 155 | sortedTimers_.erase(sortedTimers_.begin()); |
| 156 | auto result = write(fd_[1], &timer->id, sizeof(int)); |
| 157 | if (result == -1 && errno == EAGAIN) { |
| 158 | isBufferFull = true; |
| 159 | while (!stopped && deletedTimers_.find(timer->id) != deletedTimers_.end() && |
| 160 | write(fd_[1], &timer->id, sizeof(int)) == -1 && errno == EAGAIN) { |
| 161 | bufferFull.wait(lk); |
| 162 | } |
| 163 | } else if (isBufferFull.load() && |
| 164 | (sortedTimers_.empty() || sortedTimers_.at(0)->dueTime > now)) { |
| 165 | // we had a successful write and the next timer is not due |
| 166 | // mark the buffer as free to re-enable the setTimeout with 0 optimization |
| 167 | isBufferFull = false; |
| 168 | } |
| 169 | } else { |
| 170 | taskReady.wait_for(lk, std::chrono::milliseconds((int) (timer->dueTime - now))); |
| 171 | } |
| 172 | } else { |
| 173 | taskReady.wait(lk); |
| 174 | } |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | void Timers::Destroy() { |
| 179 | { |