C/C++ API Reference
Loading...
Searching...
No Matches
time_provider.h
1// Copyright 2024 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15#pragma once
16
17#include <stddef.h>
18
19#include <mutex>
20
21#include "pw_async2/dispatcher.h"
22#include "pw_async2/future.h"
23#include "pw_chrono/virtual_clock.h"
24#include "pw_containers/intrusive_list.h"
25#include "pw_sync/interrupt_spin_lock.h"
26#include "pw_sync/lock_annotations.h"
27#include "pw_toolchain/no_destructor.h"
28
29namespace pw::async2 {
30
31namespace internal {
32
33// A lock which guards `TimeProvider`'s linked list.
34inline pw::sync::InterruptSpinLock& time_lock() {
36 return lock;
37}
38
39// `Timer` objects must not outlive their `TimeProvider`.
40void AssertTimeFutureObjectsAllGone(bool empty);
41
42} // namespace internal
43
45
46template <typename Clock>
47class TimeFuture;
48
62template <typename Clock>
63class TimeProvider : public chrono::VirtualClock<Clock> {
64 public:
65 ~TimeProvider() override {
66 internal::AssertTimeFutureObjectsAllGone(futures_.empty());
67 }
68
69 typename Clock::time_point now() override = 0;
70
75 [[nodiscard]] TimeFuture<Clock> WaitFor(typename Clock::duration delay) {
80 return WaitUntil(now() + delay + typename Clock::duration(1));
81 }
82
88 typename Clock::time_point timestamp) {
89 return TimeFuture<Clock>(*this, timestamp);
90 }
91
92 protected:
97 void RunExpired(typename Clock::time_point now)
98 PW_LOCKS_EXCLUDED(internal::time_lock());
99
100 private:
101 friend class TimeFuture<Clock>;
102
105 virtual void DoInvokeAt(typename Clock::time_point)
106 PW_EXCLUSIVE_LOCKS_REQUIRED(internal::time_lock()) = 0;
107
109 virtual void DoCancel()
110 PW_EXCLUSIVE_LOCKS_REQUIRED(internal::time_lock()) = 0;
111
112 // Head of the waiting timers list.
113 IntrusiveList<TimeFuture<Clock>> futures_
114 PW_GUARDED_BY(internal::time_lock());
115};
116
121template <typename Clock>
122class [[nodiscard]] TimeFuture
123 : public Future<TimeFuture<Clock>, typename Clock::time_point>,
124 public IntrusiveForwardList<TimeFuture<Clock>>::Item {
125 public:
126 TimeFuture() : provider_(nullptr) {}
127 TimeFuture(const TimeFuture&) = delete;
128 TimeFuture& operator=(const TimeFuture&) = delete;
129
130 TimeFuture(TimeFuture&& other) : provider_(nullptr) {
131 *this = std::move(other);
132 }
133
134 TimeFuture& operator=(TimeFuture&& other) {
135 std::lock_guard lock(internal::time_lock());
136 UnlistLocked();
137
138 provider_ = other.provider_;
139 expiration_ = other.expiration_;
140
141 // Replace the entry of `other_` in the list.
142 if (!other.unlisted()) {
143 auto previous = provider_->futures_.before_begin();
144 while (&*std::next(previous) != &other) {
145 previous++;
146 }
147
148 // NOTE: this will leave `other` reporting (falsely) that it has expired.
149 // However, `other` should not be used post-`move`.
150 other.unlist(&*previous);
151 provider_->futures_.insert_after(previous, *this);
152 }
153
154 return *this;
155 }
156
160 ~TimeFuture() { Unlist(); }
161
162 // Returns the provider associated with this timer.
163 //
164 // NOTE: this method must not be called before initializing the timer.
166 // A lock is not required because this value is only mutated in
167 // constructors.
168 return *provider_;
169 }
170
171 // Returns the provider associated with this timer.
172 //
173 // NOTE: this method must not be called before initializing the timer.
174 // NOTE: this method must not be called with other methods that modify
175 // the expiration time such as `Reset`.
176 typename Clock::time_point expiration() PW_NO_LOCK_SAFETY_ANALYSIS {
177 // A lock is not required because this is only mutated in ``Reset`` and
178 // constructors.
179 return expiration_;
180 }
181
182 private:
183 using Base = Future<TimeFuture<Clock>, typename Clock::time_point>;
184 friend Base;
185 friend class TimeProvider<Clock>;
186
187 Poll<typename Clock::time_point> DoPend(Context& cx)
188 PW_LOCKS_EXCLUDED(internal::time_lock()) {
189 std::lock_guard lock(internal::time_lock());
190 if (this->unlisted()) {
191 return Ready(expiration_);
192 }
193 // NOTE: this is done under the lock in order to ensure that `provider_` is
194 // not set to unlisted between it being initially read and `waker_` being
195 // set.
196 PW_ASYNC_STORE_WAKER(cx, waker_, "TimeFuture is waiting for a time_point");
197 return Pending();
198 }
199
200 void DoMarkComplete() {
201 std::lock_guard lock(internal::time_lock());
202 provider_ = nullptr;
203 }
204
205 // SAFETY: It is safe to read `provider_` without holding the lock.
206 bool DoIsComplete() const PW_NO_LOCK_SAFETY_ANALYSIS {
207 return provider_ == nullptr;
208 }
209
211 TimeFuture(TimeProvider<Clock>& provider,
212 typename Clock::time_point expiration)
213 : waker_(), provider_(&provider), expiration_(expiration) {
214 std::lock_guard lock(internal::time_lock());
215 EnlistLocked();
216 }
217
218 void EnlistLocked() PW_EXCLUSIVE_LOCKS_REQUIRED(internal::time_lock()) {
219 // Skip enlisting if the expiration of the timer is in the past.
220 // NOTE: this *does not* trigger a waker since `Poll` has not yet been
221 // invoked, so none has been registered.
222 if (provider_->now() >= expiration_) {
223 return;
224 }
225
226 if (provider_->futures_.empty() ||
227 provider_->futures_.front().expiration_ > expiration_) {
228 provider_->futures_.push_front(*this);
229 provider_->DoInvokeAt(expiration_);
230 return;
231 }
232 auto current = provider_->futures_.begin();
233 while (std::next(current) != provider_->futures_.end() &&
234 std::next(current)->expiration_ < expiration_) {
235 current++;
236 }
237 provider_->futures_.insert_after(current, *this);
238 }
239
240 void Unlist() PW_LOCKS_EXCLUDED(internal::time_lock()) {
241 std::lock_guard lock(internal::time_lock());
242 UnlistLocked();
243 }
244
245 // Removes this timer from the `TimeProvider`'s list (if listed).
246 //
247 // If this timer was previously the `head` element of the `TimeProvider`'s
248 // list, the `TimeProvider` will be rescheduled to wake up based on the
249 // new `head`'s expiration time.
250 void UnlistLocked() PW_EXCLUSIVE_LOCKS_REQUIRED(internal::time_lock()) {
251 if (this->unlisted()) {
252 return;
253 }
254 if (&provider_->futures_.front() == this) {
255 provider_->futures_.pop_front();
256 if (provider_->futures_.empty()) {
257 provider_->DoCancel();
258 } else {
259 provider_->DoInvokeAt(provider_->futures_.front().expiration_);
260 }
261 return;
262 }
263
264 provider_->futures_.remove(*this);
265 }
266
267 Waker waker_;
268 // NOTE: the lock is only required when
269 // (1) modifying these fields or
270 // (2) reading these fields via the TimeProvider.
271 //
272 // Reading these fields when nonmodification is guaranteed (such as in an
273 // accessor like ``provider`` or ``expiration`` above) does not require
274 // holding the lock.
275 TimeProvider<Clock>* provider_ PW_GUARDED_BY(internal::time_lock());
276 typename Clock::time_point expiration_ PW_GUARDED_BY(internal::time_lock());
277};
278
279template <typename Clock>
280void TimeProvider<Clock>::RunExpired(typename Clock::time_point now) {
281 std::lock_guard lock(internal::time_lock());
282 while (!futures_.empty()) {
283 if (futures_.front().expiration_ > now) {
284 DoInvokeAt(futures_.front().expiration_);
285 return;
286 }
287 std::move(futures_.front().waker_).Wake();
288 futures_.pop_front();
289 }
290}
291
293
294} // namespace pw::async2
Definition: intrusive_forward_list.h:91
Definition: future.h:62
Definition: time_provider.h:124
~TimeFuture()
Definition: time_provider.h:160
Definition: time_provider.h:63
virtual void DoCancel()=0
Optimistically cancels all pending DoInvokeAt requests.
Clock::time_point now() override=0
Returns the current time.
TimeFuture< Clock > WaitFor(typename Clock::duration delay)
Definition: time_provider.h:75
virtual void DoInvokeAt(typename Clock::time_point)=0
TimeFuture< Clock > WaitUntil(typename Clock::time_point timestamp)
Definition: time_provider.h:87
Definition: virtual_clock.h:31
Definition: intrusive_list.h:88
Definition: interrupt_spin_lock.h:50
constexpr PendingType Pending()
Returns a value indicating that an operation was not yet able to complete.
Definition: poll.h:271
#define PW_ASYNC_STORE_WAKER(context, waker_or_queue_out, wait_reason_string)
Definition: waker.h:60
constexpr Poll Ready()
Returns a value indicating completion.
Definition: poll.h:255
void RunExpired(typename Clock::time_point now)
Definition: time_provider.h:280
#define PW_GUARDED_BY(x)
Definition: lock_annotations.h:60
#define PW_NO_LOCK_SAFETY_ANALYSIS
Definition: lock_annotations.h:292
#define PW_EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: lock_annotations.h:146
#define PW_LOCKS_EXCLUDED(...)
Definition: lock_annotations.h:176