timer_queue.hpp 10 KB

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