Advertisement
Guest User

TimerEventFunction

a guest
Apr 8th, 2020
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.44 KB | None | 0 0
  1. class TimerEventManager
  2. {
  3. public:
  4.     using steady_clock_t = std::chrono::steady_clock;
  5.     using time_point_t = steady_clock_t::time_point;
  6.     using duration_t = steady_clock_t::duration;
  7.  
  8.     void dispatch_timer_event(TimerEventFunction&& timer_evt) {
  9.         std::unique_lock<std::mutex> lock(queue_mutex_);
  10.         const bool was_empty = queue_.empty();
  11.         queue_.push(std::move(timer_evt));
  12.         if (!was_empty) {
  13.             was_awakened = true;
  14.         }
  15.         cv_.notify_one();
  16.     }
  17.  
  18.     void execute_next_in_line() {
  19.         std::unique_lock<std::mutex> lock(queue_mutex_);
  20.         queue_.top().execute();
  21.         queue_.pop();
  22.     }
  23.  
  24.     [[nodiscard]] auto get_time_until_next() noexcept -> duration_t {
  25.         std::unique_lock<std::mutex> lock(queue_mutex_);
  26.         return queue_.top().duration();
  27.     }
  28.  
  29.     void wait_until_push() noexcept {
  30.         std::unique_lock<std::mutex> lock(queue_mutex_);
  31.         cv_.wait(lock, [this] { return this->queue_.empty(); });
  32.     }
  33.  
  34.     [[nodiscard]] bool wait_for(duration_t& previous) {
  35.         std::unique_lock<std::mutex> lock(queue_mutex_);
  36.         time_point_t before = steady_clock_t::now();
  37.         cv_.wait_for(lock, queue_.top().duration() - previous);
  38.         previous = steady_clock_t::now() - before;
  39.         if (was_awakened) {
  40.             was_awakened = false;
  41.             return true;
  42.         }
  43.         return false;
  44.     }
  45.  
  46. private:
  47.     std::priority_queue<TimerEventFunction, std::vector<TimerEventFunction>, std::greater<TimerEventFunction>> queue_;
  48.     std::mutex queue_mutex_;
  49.     std::condition_variable cv_;
  50.     bool was_awakened;
  51. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement