| 1 | #ifndef _WIN32 |
| 2 | |
| 3 | #include "timer_posix.h" |
| 4 | |
| 5 | int Timer::bg_main_func(void* data) { |
| 6 | reinterpret_cast<Timer*>(data)->bg_main(); |
| 7 | return 0; |
| 8 | } |
| 9 | |
| 10 | void Timer::bg_main() { |
| 11 | Guard guard(&this->mutex); |
| 12 | while (true) { |
| 13 | |
| 14 | // Guarded wait; we can't pass here until either the timer is stopped or we |
| 15 | // have a wait time. |
| 16 | while (!(this->stopped || this->wakeAt.has_value())) { |
| 17 | this->cond.wait(); |
| 18 | } |
| 19 | |
| 20 | // We're stopped; return, which ends the thread. |
| 21 | if (this->stopped) { |
| 22 | return; |
| 23 | } |
| 24 | |
| 25 | // The wake time has been set. There are three possibilities: |
| 26 | // 1. The wake time is in the past. Go ahead and execute now. |
| 27 | // 2. Wait for the wake time, but we're notified before time elapses. |
| 28 | // Start the loop again. |
| 29 | // 3. Wait for the wake time, and time elapses. Go ahead and execute now. |
| 30 | double secs = (*this->wakeAt).diff_secs(Timestamp()); |
| 31 | if (secs > 0) { |
| 32 | bool signalled = this->cond.timedwait(secs); |
| 33 | if (this->stopped) { |
| 34 | return; |
| 35 | } |
| 36 | if (signalled) { |
| 37 | // Time didn't elapse, we were woken up (probably). Start over. |
| 38 | continue; |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | this->wakeAt.reset(); |
| 43 | callback(); |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | Timer::Timer(const std::function<void ()>& callback) : |
| 48 | callback(callback), mutex(tct_mtx_recursive), cond(mutex), stopped(false) { |
| 49 | } |
| 50 | |
| 51 | Timer::~Timer() { |
| 52 | |
| 53 | // Must stop background thread before cleaning up condition variable and |
| 54 | // mutex. Calling pthread_cond_destroy on a condvar that's being waited |
| 55 | // on results in undefined behavior--on Fedora 25+ it hangs. |
| 56 | if (this->bgthread.has_value()) { |
| 57 | { |
| 58 | Guard guard(&this->mutex); |
| 59 | this->stopped = true; |
| 60 | this->cond.signal(); |
| 61 | } |
| 62 | |
| 63 | tct_thrd_join(*this->bgthread, NULL); |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | void Timer::set(const Timestamp& timestamp) { |
| 68 | Guard guard(&this->mutex); |
| 69 | |
| 70 | // If the thread has not yet been created, created it. |
| 71 | if (!this->bgthread.has_value()) { |
| 72 | tct_thrd_t thread; |
| 73 | tct_thrd_create(&thread, &bg_main_func, this); |
| 74 | this->bgthread = thread; |
| 75 | } |
| 76 | |
| 77 | this->wakeAt = timestamp; |
| 78 | this->cond.signal(); |
| 79 | } |
| 80 | |
| 81 | #endif // _WIN32 |