timer_queue.hpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. //
  2. // detail/timer_queue.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2023 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  6. //
  7. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. //
  10. #ifndef ASIO_DETAIL_TIMER_QUEUE_HPP
  11. #define ASIO_DETAIL_TIMER_QUEUE_HPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include "asio/detail/config.hpp"
  16. #include <cstddef>
  17. #include <vector>
  18. #include "asio/detail/cstdint.hpp"
  19. #include "asio/detail/date_time_fwd.hpp"
  20. #include "asio/detail/limits.hpp"
  21. #include "asio/detail/op_queue.hpp"
  22. #include "asio/detail/timer_queue_base.hpp"
  23. #include "asio/detail/wait_op.hpp"
  24. #include "asio/error.hpp"
  25. #include "asio/detail/push_options.hpp"
  26. namespace asio {
  27. namespace detail {
  28. template <typename Time_Traits>
  29. class timer_queue
  30. : public timer_queue_base
  31. {
  32. public:
  33. // The time type.
  34. typedef typename Time_Traits::time_type time_type;
  35. // The duration type.
  36. typedef typename Time_Traits::duration_type duration_type;
  37. // Per-timer data.
  38. class per_timer_data
  39. {
  40. public:
  41. per_timer_data() :
  42. heap_index_((std::numeric_limits<std::size_t>::max)()),
  43. next_(0), prev_(0)
  44. {
  45. }
  46. private:
  47. friend class timer_queue;
  48. // The operations waiting on the timer.
  49. op_queue<wait_op> op_queue_;
  50. // The index of the timer in the heap.
  51. std::size_t heap_index_;
  52. // Pointers to adjacent timers in a linked list.
  53. per_timer_data* next_;
  54. per_timer_data* prev_;
  55. };
  56. // Constructor.
  57. timer_queue()
  58. : timers_(),
  59. heap_()
  60. {
  61. }
  62. // Add a new timer to the queue. Returns true if this is the timer that is
  63. // earliest in the queue, in which case the reactor's event demultiplexing
  64. // function call may need to be interrupted and restarted.
  65. bool enqueue_timer(const time_type& time, per_timer_data& timer, wait_op* op)
  66. {
  67. // Enqueue the timer object.
  68. if (timer.prev_ == 0 && &timer != timers_)
  69. {
  70. if (this->is_positive_infinity(time))
  71. {
  72. // No heap entry is required for timers that never expire.
  73. timer.heap_index_ = (std::numeric_limits<std::size_t>::max)();
  74. }
  75. else
  76. {
  77. // Put the new timer at the correct position in the heap. This is done
  78. // first since push_back() can throw due to allocation failure.
  79. timer.heap_index_ = heap_.size();
  80. heap_entry entry = { time, &timer };
  81. heap_.push_back(entry);
  82. up_heap(heap_.size() - 1);
  83. }
  84. // Insert the new timer into the linked list of active timers.
  85. timer.next_ = timers_;
  86. timer.prev_ = 0;
  87. if (timers_)
  88. timers_->prev_ = &timer;
  89. timers_ = &timer;
  90. }
  91. // Enqueue the individual timer operation.
  92. timer.op_queue_.push(op);
  93. // Interrupt reactor only if newly added timer is first to expire.
  94. return timer.heap_index_ == 0 && timer.op_queue_.front() == op;
  95. }
  96. // Whether there are no timers in the queue.
  97. virtual bool empty() const
  98. {
  99. return timers_ == 0;
  100. }
  101. // Get the time for the timer that is earliest in the queue.
  102. virtual long wait_duration_msec(long max_duration) const
  103. {
  104. if (heap_.empty())
  105. return max_duration;
  106. return this->to_msec(
  107. Time_Traits::to_posix_duration(
  108. Time_Traits::subtract(heap_[0].time_, Time_Traits::now())),
  109. max_duration);
  110. }
  111. // Get the time for the timer that is earliest in the queue.
  112. virtual long wait_duration_usec(long max_duration) const
  113. {
  114. if (heap_.empty())
  115. return max_duration;
  116. return this->to_usec(
  117. Time_Traits::to_posix_duration(
  118. Time_Traits::subtract(heap_[0].time_, Time_Traits::now())),
  119. max_duration);
  120. }
  121. // Dequeue all timers not later than the current time.
  122. virtual void get_ready_timers(op_queue<operation>& ops)
  123. {
  124. if (!heap_.empty())
  125. {
  126. const time_type now = Time_Traits::now();
  127. while (!heap_.empty() && !Time_Traits::less_than(now, heap_[0].time_))
  128. {
  129. per_timer_data* timer = heap_[0].timer_;
  130. while (wait_op* op = timer->op_queue_.front())
  131. {
  132. timer->op_queue_.pop();
  133. op->ec_ = asio::error_code();
  134. ops.push(op);
  135. }
  136. remove_timer(*timer);
  137. }
  138. }
  139. }
  140. // Dequeue all timers.
  141. virtual void get_all_timers(op_queue<operation>& ops)
  142. {
  143. while (timers_)
  144. {
  145. per_timer_data* timer = timers_;
  146. timers_ = timers_->next_;
  147. ops.push(timer->op_queue_);
  148. timer->next_ = 0;
  149. timer->prev_ = 0;
  150. }
  151. heap_.clear();
  152. }
  153. // Cancel and dequeue operations for the given timer.
  154. std::size_t cancel_timer(per_timer_data& timer, op_queue<operation>& ops,
  155. std::size_t max_cancelled = (std::numeric_limits<std::size_t>::max)())
  156. {
  157. std::size_t num_cancelled = 0;
  158. if (timer.prev_ != 0 || &timer == timers_)
  159. {
  160. while (wait_op* op = (num_cancelled != max_cancelled)
  161. ? timer.op_queue_.front() : 0)
  162. {
  163. op->ec_ = asio::error::operation_aborted;
  164. timer.op_queue_.pop();
  165. ops.push(op);
  166. ++num_cancelled;
  167. }
  168. if (timer.op_queue_.empty())
  169. remove_timer(timer);
  170. }
  171. return num_cancelled;
  172. }
  173. // Cancel and dequeue a specific operation for the given timer.
  174. void cancel_timer_by_key(per_timer_data* timer,
  175. op_queue<operation>& ops, void* cancellation_key)
  176. {
  177. if (timer->prev_ != 0 || timer == timers_)
  178. {
  179. op_queue<wait_op> other_ops;
  180. while (wait_op* op = timer->op_queue_.front())
  181. {
  182. timer->op_queue_.pop();
  183. if (op->cancellation_key_ == cancellation_key)
  184. {
  185. op->ec_ = asio::error::operation_aborted;
  186. ops.push(op);
  187. }
  188. else
  189. other_ops.push(op);
  190. }
  191. timer->op_queue_.push(other_ops);
  192. if (timer->op_queue_.empty())
  193. remove_timer(*timer);
  194. }
  195. }
  196. // Move operations from one timer to another, empty timer.
  197. void move_timer(per_timer_data& target, per_timer_data& source)
  198. {
  199. target.op_queue_.push(source.op_queue_);
  200. target.heap_index_ = source.heap_index_;
  201. source.heap_index_ = (std::numeric_limits<std::size_t>::max)();
  202. if (target.heap_index_ < heap_.size())
  203. heap_[target.heap_index_].timer_ = &target;
  204. if (timers_ == &source)
  205. timers_ = &target;
  206. if (source.prev_)
  207. source.prev_->next_ = &target;
  208. if (source.next_)
  209. source.next_->prev_= &target;
  210. target.next_ = source.next_;
  211. target.prev_ = source.prev_;
  212. source.next_ = 0;
  213. source.prev_ = 0;
  214. }
  215. private:
  216. // Move the item at the given index up the heap to its correct position.
  217. void up_heap(std::size_t index)
  218. {
  219. while (index > 0)
  220. {
  221. std::size_t parent = (index - 1) / 2;
  222. if (!Time_Traits::less_than(heap_[index].time_, heap_[parent].time_))
  223. break;
  224. swap_heap(index, parent);
  225. index = parent;
  226. }
  227. }
  228. // Move the item at the given index down the heap to its correct position.
  229. void down_heap(std::size_t index)
  230. {
  231. std::size_t child = index * 2 + 1;
  232. while (child < heap_.size())
  233. {
  234. std::size_t min_child = (child + 1 == heap_.size()
  235. || Time_Traits::less_than(
  236. heap_[child].time_, heap_[child + 1].time_))
  237. ? child : child + 1;
  238. if (Time_Traits::less_than(heap_[index].time_, heap_[min_child].time_))
  239. break;
  240. swap_heap(index, min_child);
  241. index = min_child;
  242. child = index * 2 + 1;
  243. }
  244. }
  245. // Swap two entries in the heap.
  246. void swap_heap(std::size_t index1, std::size_t index2)
  247. {
  248. heap_entry tmp = heap_[index1];
  249. heap_[index1] = heap_[index2];
  250. heap_[index2] = tmp;
  251. heap_[index1].timer_->heap_index_ = index1;
  252. heap_[index2].timer_->heap_index_ = index2;
  253. }
  254. // Remove a timer from the heap and list of timers.
  255. void remove_timer(per_timer_data& timer)
  256. {
  257. // Remove the timer from the heap.
  258. std::size_t index = timer.heap_index_;
  259. if (!heap_.empty() && index < heap_.size())
  260. {
  261. if (index == heap_.size() - 1)
  262. {
  263. timer.heap_index_ = (std::numeric_limits<std::size_t>::max)();
  264. heap_.pop_back();
  265. }
  266. else
  267. {
  268. swap_heap(index, heap_.size() - 1);
  269. timer.heap_index_ = (std::numeric_limits<std::size_t>::max)();
  270. heap_.pop_back();
  271. if (index > 0 && Time_Traits::less_than(
  272. heap_[index].time_, heap_[(index - 1) / 2].time_))
  273. up_heap(index);
  274. else
  275. down_heap(index);
  276. }
  277. }
  278. // Remove the timer from the linked list of active timers.
  279. if (timers_ == &timer)
  280. timers_ = timer.next_;
  281. if (timer.prev_)
  282. timer.prev_->next_ = timer.next_;
  283. if (timer.next_)
  284. timer.next_->prev_= timer.prev_;
  285. timer.next_ = 0;
  286. timer.prev_ = 0;
  287. }
  288. // Determine if the specified absolute time is positive infinity.
  289. template <typename Time_Type>
  290. static bool is_positive_infinity(const Time_Type&)
  291. {
  292. return false;
  293. }
  294. // Determine if the specified absolute time is positive infinity.
  295. template <typename T, typename TimeSystem>
  296. static bool is_positive_infinity(
  297. const boost::date_time::base_time<T, TimeSystem>& time)
  298. {
  299. return time.is_pos_infinity();
  300. }
  301. // Helper function to convert a duration into milliseconds.
  302. template <typename Duration>
  303. long to_msec(const Duration& d, long max_duration) const
  304. {
  305. if (d.ticks() <= 0)
  306. return 0;
  307. int64_t msec = d.total_milliseconds();
  308. if (msec == 0)
  309. return 1;
  310. if (msec > max_duration)
  311. return max_duration;
  312. return static_cast<long>(msec);
  313. }
  314. // Helper function to convert a duration into microseconds.
  315. template <typename Duration>
  316. long to_usec(const Duration& d, long max_duration) const
  317. {
  318. if (d.ticks() <= 0)
  319. return 0;
  320. int64_t usec = d.total_microseconds();
  321. if (usec == 0)
  322. return 1;
  323. if (usec > max_duration)
  324. return max_duration;
  325. return static_cast<long>(usec);
  326. }
  327. // The head of a linked list of all active timers.
  328. per_timer_data* timers_;
  329. struct heap_entry
  330. {
  331. // The time when the timer should fire.
  332. time_type time_;
  333. // The associated timer with enqueued operations.
  334. per_timer_data* timer_;
  335. };
  336. // The heap of timers, with the earliest timer at the front.
  337. std::vector<heap_entry> heap_;
  338. };
  339. } // namespace detail
  340. } // namespace asio
  341. #include "asio/detail/pop_options.hpp"
  342. #endif // ASIO_DETAIL_TIMER_QUEUE_HPP