timer_queue.hpp 11 KB

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