VLink  2.0.0
A high-performance communication middleware
deadline_timer.h
浏览该文件的文档.
1 /*
2  * Copyright (C) 2026 by Thun Lu. All rights reserved.
3  * Author: Thun Lu <thun.lu@zohomail.cn>
4  * Repo: https://github.com/thun-res/vlink
5  * _ __ __ _ __
6  * | | / / / / (_) ____ / /__
7  * | | / / / / / / / __ \ / //_/
8  * | |/ / / /___ / / / / / / / ,<
9  * |___/ /_____/ /_/ /_/ /_/ /_/|_|
10  *
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  * http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  */
23 
24 /**
25  * @file deadline_timer.h
26  * @brief Atomic absolute-deadline timer used for lock-free timeout tracking on hot paths.
27  *
28  * @details
29  * @c DeadlineTimer stores a single absolute monotonic timestamp inside a 64-bit atomic, which
30  * makes deadline checks branch-light and concurrent reads safe without external locking. It is
31  * used inside connection bookkeeping and RPC request tracking to detect expired operations.
32  *
33  * @par State diagram
34  *
35  * @verbatim
36  * +--------+ set_deadline / set_deadline_abs +---------+ now >= deadline +----------+
37  * | idle | ------------------------------> | armed | --------------> | expired |
38  * | (zero) | | | +----------+
39  * +--------+ <------- reset() --------------- +---------+ |
40  * ^ |
41  * +----------------------- reset() / set 0 --------------------------------+
42  * @endverbatim
43  *
44  * @par Comparison vs the periodic @c vlink::Timer
45  *
46  * | Aspect | @c vlink::DeadlineTimer | @c vlink::Timer |
47  * | ----------------- | -------------------------- | ----------------------------------- |
48  * | Purpose | Track a single deadline | Schedule repeating callbacks |
49  * | Backing storage | One @c atomic<uint64_t> | Loop-managed timer list |
50  * | Owns a thread | No | Owned by an attached @c MessageLoop |
51  * | Cost per check | One atomic load | Insertion / removal on the loop |
52  * | Cancellation | @c reset() | @c detach() on the timer instance |
53  *
54  * @par Example
55  * @code
56  * vlink::DeadlineTimer t(200); // 200 ms from now
57  * while (!t.has_expired()) {
58  * process_events();
59  * }
60  * const int64_t left = t.remaining_time(); // 0 once past deadline
61  *
62  * const uint64_t now = vlink::ElapsedTimer::get_cpu_timestamp();
63  * t.set_deadline_abs(now + 500); // absolute reset
64  * @endcode
65  */
66 
67 #pragma once
68 
69 #include <atomic>
70 #include <cstdint>
71 
72 #include "./elapsed_timer.h"
73 #include "./macros.h"
74 
75 namespace vlink {
76 
77 /**
78  * @class DeadlineTimer
79  * @brief Cache-line aligned atomic deadline counter with millisecond / microsecond / nanosecond precision.
80  *
81  * @details
82  * Reuses @c ElapsedTimer::Accuracy for time precision. Reads and writes go through a single
83  * @c std::atomic<uint64_t> aligned to 64 bytes to avoid false sharing when several timers share
84  * a structure. An invalid (unset) timer stores @c 0 and never reports expiry.
85  */
87  public:
88  /**
89  * @brief Precision unit alias inherited from @c ElapsedTimer::Accuracy.
90  */
92 
93  /**
94  * @brief Constructs an invalid timer with no deadline set.
95  *
96  * @details
97  * @c is_valid returns @c false and @c has_expired returns @c false until @c set_deadline or
98  * @c set_deadline_abs is called.
99  */
100  DeadlineTimer() noexcept;
101 
102  /**
103  * @brief Constructs a timer that expires @p interval units in the future.
104  *
105  * @details
106  * The absolute deadline is computed as the current monotonic timestamp plus @p interval. A
107  * non-positive @p interval leaves the timer invalid.
108  *
109  * @param interval Duration until expiry in @p accuracy units.
110  * @param accuracy Precision of stored timestamps. Default: @c ElapsedTimer::kMilli.
111  */
112  explicit DeadlineTimer(int64_t interval, Accuracy accuracy = ElapsedTimer::kMilli) noexcept;
113 
114  /**
115  * @brief Copy constructor; copies the stored deadline and accuracy.
116  *
117  * @param other Source timer.
118  */
119  DeadlineTimer(const DeadlineTimer& other) noexcept;
120 
121  /**
122  * @brief Move constructor; equivalent to copy because the timer holds only POD state.
123  *
124  * @param other Source timer.
125  */
126  DeadlineTimer(DeadlineTimer&& other) noexcept;
127 
128  /**
129  * @brief Destructor.
130  */
131  ~DeadlineTimer() noexcept;
132 
133  /**
134  * @brief Copy assignment; replaces the stored deadline and accuracy.
135  *
136  * @param other Source timer.
137  * @return Reference to @c *this.
138  */
139  DeadlineTimer& operator=(const DeadlineTimer& other) noexcept;
140 
141  /**
142  * @brief Move assignment; equivalent to copy assignment for this POD-state type.
143  *
144  * @param other Source timer.
145  * @return Reference to @c *this.
146  */
147  DeadlineTimer& operator=(DeadlineTimer&& other) noexcept;
148 
149  /**
150  * @brief Sets the deadline @p interval units after the current monotonic timestamp.
151  *
152  * @details
153  * A non-positive @p interval clears the timer (equivalent to @c reset).
154  *
155  * @param interval Duration until expiry in the configured accuracy unit.
156  */
157  void set_deadline(int64_t interval) noexcept;
158 
159  /**
160  * @brief Sets an absolute deadline timestamp directly.
161  *
162  * @details
163  * @p abs_deadline must be expressed in the same unit and time base as the configured accuracy;
164  * obtain it via @c ElapsedTimer::get_cpu_timestamp(accuracy).
165  *
166  * @param abs_deadline Absolute monotonic deadline.
167  */
168  void set_deadline_abs(uint64_t abs_deadline) noexcept;
169 
170  /**
171  * @brief Resets the timer to the invalid state.
172  *
173  * @details
174  * After @c reset, @c is_valid returns @c false and @c has_expired returns @c false.
175  */
176  void reset() noexcept;
177 
178  /**
179  * @brief Returns the stored absolute deadline timestamp.
180  *
181  * @return Deadline value in the configured accuracy unit. @c 0 indicates an invalid timer.
182  */
183  [[nodiscard]] uint64_t deadline() const noexcept;
184 
185  /**
186  * @brief Returns the time remaining until the deadline.
187  *
188  * @details
189  * Computed as @c (deadline - current_cpu_timestamp); clamped to @c 0 once the deadline has
190  * been reached or when the timer is invalid.
191  *
192  * @return Remaining time in the configured accuracy unit; @c 0 when invalid or expired.
193  */
194  [[nodiscard]] int64_t remaining_time() const noexcept;
195 
196  /**
197  * @brief Reports whether the current time has passed the stored deadline.
198  *
199  * @return @c true when expired; always @c false for invalid timers.
200  */
201  [[nodiscard]] bool has_expired() const noexcept;
202 
203  /**
204  * @brief Reports whether a deadline has been set.
205  *
206  * @return @c true when @c deadline() is non-zero.
207  */
208  [[nodiscard]] bool is_valid() const noexcept;
209 
210  /**
211  * @brief Returns the precision configured for this timer.
212  *
213  * @return Accuracy unit chosen at construction.
214  */
215  [[nodiscard]] Accuracy get_accuracy() const noexcept;
216 
217  private:
218  alignas(64) std::atomic<uint64_t> deadline_{0};
219  Accuracy accuracy_{ElapsedTimer::kMilli};
220 };
221 
222 } // namespace vlink
Lowest-level elapsed-time primitive used by deadline tracking, profilers and task metrics.
Cross-platform macros for visibility, branch hints, copy prevention, singletons and string helpers.
#define VLINK_EXPORT
Definition: macros.h:81