Debian Codegraph @

debian/rust-vendor/futures-timer/src/native/atomic_waker.rs

raw
1 use core::cell::UnsafeCell;
2 use core::fmt;
3 use core::sync::atomic::AtomicUsize;
4 use core::sync::atomic::Ordering::{AcqRel, Acquire, Release};
5 use core::task::Waker;
6
7 /// A synchronization primitive for task wakeup.
8 ///
9 /// Sometimes the task interested in a given event will change over time.
10 /// An `AtomicWaker` can coordinate concurrent notifications with the consumer
11 /// potentially "updating" the underlying task to wake up. This is useful in
12 /// scenarios where a computation completes in another thread and wants to
13 /// notify the consumer, but the consumer is in the process of being migrated to
14 /// a new logical task.
15 ///
16 /// Consumers should call `register` before checking the result of a computation
17 /// and producers should call `wake` after producing the computation (this
18 /// differs from the usual `thread::park` pattern). It is also permitted for
19 /// `wake` to be called **before** `register`. This results in a no-op.
20 ///
21 /// A single `AtomicWaker` may be reused for any number of calls to `register` or
22 /// `wake`.
23 ///
24 /// `AtomicWaker` does not provide any memory ordering guarantees, as such the
25 /// user should use caution and use other synchronization primitives to guard
26 /// the result of the underlying computation.
27 pub struct AtomicWaker {
28 state: AtomicUsize,
29 waker: UnsafeCell<Option<Waker>>,
30 }
31
32 /// Idle state
33 const WAITING: usize = 0;
34
35 /// A new waker value is being registered with the `AtomicWaker` cell.
36 const REGISTERING: usize = 0b01;
37
38 /// The waker currently registered with the `AtomicWaker` cell is being woken.
39 const WAKING: usize = 0b10;
40
41 impl AtomicWaker {
42 /// Create an `AtomicWaker`.
43 pub fn new() -> AtomicWaker {
44 AtomicWaker {
45 state: AtomicUsize::new(WAITING),
46 waker: UnsafeCell::new(None),
47 }
48 }
49
50 /// Registers the waker to be notified on calls to `wake`.
51 ///
52 /// The new task will take place of any previous tasks that were registered
53 /// by previous calls to `register`. Any calls to `wake` that happen after
54 /// a call to `register` (as defined by the memory ordering rules), will
55 /// notify the `register` caller's task and deregister the waker from future
56 /// notifications. Because of this, callers should ensure `register` gets
57 /// invoked with a new `Waker` **each** time they require a wakeup.
58 ///
59 /// It is safe to call `register` with multiple other threads concurrently
60 /// calling `wake`. This will result in the `register` caller's current
61 /// task being notified once.
62 ///
63 /// This function is safe to call concurrently, but this is generally a bad
64 /// idea. Concurrent calls to `register` will attempt to register different
65 /// tasks to be notified. One of the callers will win and have its task set,
66 /// but there is no guarantee as to which caller will succeed.
67 ///
68 /// # Examples
69 ///
70 /// Here is how `register` is used when implementing a flag.
71 ///
72 /// ```
73 /// use std::future::Future;
74 /// use std::task::{Context, Poll};
75 /// use std::sync::atomic::AtomicBool;
76 /// use std::sync::atomic::Ordering::SeqCst;
77 /// use std::pin::Pin;
78 ///
79 /// use futures::task::AtomicWaker;
80 ///
81 /// struct Flag {
82 /// waker: AtomicWaker,
83 /// set: AtomicBool,
84 /// }
85 ///
86 /// impl Future for Flag {
87 /// type Output = ();
88 ///
89 /// fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
90 /// // Register **before** checking `set` to avoid a race condition
91 /// // that would result in lost notifications.
92 /// self.waker.register(cx.waker());
93 ///
94 /// if self.set.load(SeqCst) {
95 /// Poll::Ready(())
96 /// } else {
97 /// Poll::Pending
98 /// }
99 /// }
100 /// }
101 /// ```
102 pub fn register(&self, waker: &Waker) {
103 match self
104 .state
105 .compare_exchange(WAITING, REGISTERING, Acquire, Acquire)
106 {
107 Ok(_) => {
108 unsafe {
109 // Locked acquired, update the waker cell
110 *self.waker.get() = Some(waker.clone());
111
112 // Release the lock. If the state transitioned to include
113 // the `WAKING` bit, this means that a wake has been
114 // called concurrently, so we have to remove the waker and
115 // wake it.`
116 //
117 // Start by assuming that the state is `REGISTERING` as this
118 // is what we jut set it to.
119 let res = self
120 .state
121 .compare_exchange(REGISTERING, WAITING, AcqRel, Acquire);
122
123 match res {
124 Ok(_) => {}
125 Err(actual) => {
126 // This branch can only be reached if a
127 // concurrent thread called `wake`. In this
128 // case, `actual` **must** be `REGISTERING |
129 // `WAKING`.
130 debug_assert_eq!(actual, REGISTERING | WAKING);
131
132 // Take the waker to wake once the atomic operation has
133 // completed.
134 let waker = (*self.waker.get()).take().unwrap();
135
136 // Just swap, because no one could change state while state == `REGISTERING` | `WAKING`.
137 self.state.swap(WAITING, AcqRel);
138
139 // The atomic swap was complete, now
140 // wake the task and return.
141 waker.wake();
142 }
143 }
144 }
145 }
146 Err(WAKING) => {
147 // Currently in the process of waking the task, i.e.,
148 // `wake` is currently being called on the old task handle.
149 // So, we call wake on the new waker
150 waker.wake_by_ref();
151 }
152 Err(state) => {
153 // In this case, a concurrent thread is holding the
154 // "registering" lock. This probably indicates a bug in the
155 // caller's code as racing to call `register` doesn't make much
156 // sense.
157 //
158 // We just want to maintain memory safety. It is ok to drop the
159 // call to `register`.
160 debug_assert!(state == REGISTERING || state == REGISTERING | WAKING);
161 }
162 }
163 }
164
165 /// Calls `wake` on the last `Waker` passed to `register`.
166 ///
167 /// If `register` has not been called yet, then this does nothing.
168 pub fn wake(&self) {
169 if let Some(waker) = self.take() {
170 waker.wake();
171 }
172 }
173
174 /// Returns the last `Waker` passed to `register`, so that the user can wake it.
175 ///
176 ///
177 /// Sometimes, just waking the AtomicWaker is not fine grained enough. This allows the user
178 /// to take the waker and then wake it separately, rather than performing both steps in one
179 /// atomic action.
180 ///
181 /// If a waker has not been registered, this returns `None`.
182 pub fn take(&self) -> Option<Waker> {
183 // AcqRel ordering is used in order to acquire the value of the `task`
184 // cell as well as to establish a `release` ordering with whatever
185 // memory the `AtomicWaker` is associated with.
186 match self.state.fetch_or(WAKING, AcqRel) {
187 WAITING => {
188 // The waking lock has been acquired.
189 let waker = unsafe { (*self.waker.get()).take() };
190
191 // Release the lock
192 self.state.fetch_and(!WAKING, Release);
193
194 waker
195 }
196 state => {
197 // There is a concurrent thread currently updating the
198 // associated task.
199 //
200 // Nothing more to do as the `WAKING` bit has been set. It
201 // doesn't matter if there are concurrent registering threads or
202 // not.
203 //
204 debug_assert!(
205 state == REGISTERING || state == REGISTERING | WAKING || state == WAKING
206 );
207 None
208 }
209 }
210 }
211 }
212
213 impl Default for AtomicWaker {
214 fn default() -> Self {
215 AtomicWaker::new()
216 }
217 }
218
219 impl fmt::Debug for AtomicWaker {
220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221 write!(f, "AtomicWaker")
222 }
223 }
224
225 unsafe impl Send for AtomicWaker {}
226 unsafe impl Sync for AtomicWaker {}