]> git.lizzy.rs Git - rust.git/blob - library/core/src/task/wake.rs
Auto merge of #99505 - joboet:futex_once, r=thomcc
[rust.git] / library / core / src / task / wake.rs
1 #![stable(feature = "futures_api", since = "1.36.0")]
2
3 use crate::fmt;
4 use crate::marker::{PhantomData, Unpin};
5
6 /// A `RawWaker` allows the implementor of a task executor to create a [`Waker`]
7 /// which provides customized wakeup behavior.
8 ///
9 /// [vtable]: https://en.wikipedia.org/wiki/Virtual_method_table
10 ///
11 /// It consists of a data pointer and a [virtual function pointer table (vtable)][vtable]
12 /// that customizes the behavior of the `RawWaker`.
13 #[derive(PartialEq, Debug)]
14 #[stable(feature = "futures_api", since = "1.36.0")]
15 pub struct RawWaker {
16     /// A data pointer, which can be used to store arbitrary data as required
17     /// by the executor. This could be e.g. a type-erased pointer to an `Arc`
18     /// that is associated with the task.
19     /// The value of this field gets passed to all functions that are part of
20     /// the vtable as the first parameter.
21     data: *const (),
22     /// Virtual function pointer table that customizes the behavior of this waker.
23     vtable: &'static RawWakerVTable,
24 }
25
26 impl RawWaker {
27     /// Creates a new `RawWaker` from the provided `data` pointer and `vtable`.
28     ///
29     /// The `data` pointer can be used to store arbitrary data as required
30     /// by the executor. This could be e.g. a type-erased pointer to an `Arc`
31     /// that is associated with the task.
32     /// The value of this pointer will get passed to all functions that are part
33     /// of the `vtable` as the first parameter.
34     ///
35     /// The `vtable` customizes the behavior of a `Waker` which gets created
36     /// from a `RawWaker`. For each operation on the `Waker`, the associated
37     /// function in the `vtable` of the underlying `RawWaker` will be called.
38     #[inline]
39     #[rustc_promotable]
40     #[stable(feature = "futures_api", since = "1.36.0")]
41     #[rustc_const_stable(feature = "futures_api", since = "1.36.0")]
42     #[must_use]
43     pub const fn new(data: *const (), vtable: &'static RawWakerVTable) -> RawWaker {
44         RawWaker { data, vtable }
45     }
46
47     /// Get the `data` pointer used to create this `RawWaker`.
48     #[inline]
49     #[must_use]
50     #[unstable(feature = "waker_getters", issue = "87021")]
51     pub fn data(&self) -> *const () {
52         self.data
53     }
54
55     /// Get the `vtable` pointer used to create this `RawWaker`.
56     #[inline]
57     #[must_use]
58     #[unstable(feature = "waker_getters", issue = "87021")]
59     pub fn vtable(&self) -> &'static RawWakerVTable {
60         self.vtable
61     }
62 }
63
64 /// A virtual function pointer table (vtable) that specifies the behavior
65 /// of a [`RawWaker`].
66 ///
67 /// The pointer passed to all functions inside the vtable is the `data` pointer
68 /// from the enclosing [`RawWaker`] object.
69 ///
70 /// The functions inside this struct are only intended to be called on the `data`
71 /// pointer of a properly constructed [`RawWaker`] object from inside the
72 /// [`RawWaker`] implementation. Calling one of the contained functions using
73 /// any other `data` pointer will cause undefined behavior.
74 ///
75 /// These functions must all be thread-safe (even though [`RawWaker`] is
76 /// <code>\![Send] + \![Sync]</code>)
77 /// because [`Waker`] is <code>[Send] + [Sync]</code>, and thus wakers may be moved to
78 /// arbitrary threads or invoked by `&` reference. For example, this means that if the
79 /// `clone` and `drop` functions manage a reference count, they must do so atomically.
80 #[stable(feature = "futures_api", since = "1.36.0")]
81 #[derive(PartialEq, Copy, Clone, Debug)]
82 pub struct RawWakerVTable {
83     /// This function will be called when the [`RawWaker`] gets cloned, e.g. when
84     /// the [`Waker`] in which the [`RawWaker`] is stored gets cloned.
85     ///
86     /// The implementation of this function must retain all resources that are
87     /// required for this additional instance of a [`RawWaker`] and associated
88     /// task. Calling `wake` on the resulting [`RawWaker`] should result in a wakeup
89     /// of the same task that would have been awoken by the original [`RawWaker`].
90     clone: unsafe fn(*const ()) -> RawWaker,
91
92     /// This function will be called when `wake` is called on the [`Waker`].
93     /// It must wake up the task associated with this [`RawWaker`].
94     ///
95     /// The implementation of this function must make sure to release any
96     /// resources that are associated with this instance of a [`RawWaker`] and
97     /// associated task.
98     wake: unsafe fn(*const ()),
99
100     /// This function will be called when `wake_by_ref` is called on the [`Waker`].
101     /// It must wake up the task associated with this [`RawWaker`].
102     ///
103     /// This function is similar to `wake`, but must not consume the provided data
104     /// pointer.
105     wake_by_ref: unsafe fn(*const ()),
106
107     /// This function gets called when a [`RawWaker`] gets dropped.
108     ///
109     /// The implementation of this function must make sure to release any
110     /// resources that are associated with this instance of a [`RawWaker`] and
111     /// associated task.
112     drop: unsafe fn(*const ()),
113 }
114
115 impl RawWakerVTable {
116     /// Creates a new `RawWakerVTable` from the provided `clone`, `wake`,
117     /// `wake_by_ref`, and `drop` functions.
118     ///
119     /// These functions must all be thread-safe (even though [`RawWaker`] is
120     /// <code>\![Send] + \![Sync]</code>)
121     /// because [`Waker`] is <code>[Send] + [Sync]</code>, and thus wakers may be moved to
122     /// arbitrary threads or invoked by `&` reference. For example, this means that if the
123     /// `clone` and `drop` functions manage a reference count, they must do so atomically.
124     ///
125     /// # `clone`
126     ///
127     /// This function will be called when the [`RawWaker`] gets cloned, e.g. when
128     /// the [`Waker`] in which the [`RawWaker`] is stored gets cloned.
129     ///
130     /// The implementation of this function must retain all resources that are
131     /// required for this additional instance of a [`RawWaker`] and associated
132     /// task. Calling `wake` on the resulting [`RawWaker`] should result in a wakeup
133     /// of the same task that would have been awoken by the original [`RawWaker`].
134     ///
135     /// # `wake`
136     ///
137     /// This function will be called when `wake` is called on the [`Waker`].
138     /// It must wake up the task associated with this [`RawWaker`].
139     ///
140     /// The implementation of this function must make sure to release any
141     /// resources that are associated with this instance of a [`RawWaker`] and
142     /// associated task.
143     ///
144     /// # `wake_by_ref`
145     ///
146     /// This function will be called when `wake_by_ref` is called on the [`Waker`].
147     /// It must wake up the task associated with this [`RawWaker`].
148     ///
149     /// This function is similar to `wake`, but must not consume the provided data
150     /// pointer.
151     ///
152     /// # `drop`
153     ///
154     /// This function gets called when a [`RawWaker`] gets dropped.
155     ///
156     /// The implementation of this function must make sure to release any
157     /// resources that are associated with this instance of a [`RawWaker`] and
158     /// associated task.
159     #[rustc_promotable]
160     #[stable(feature = "futures_api", since = "1.36.0")]
161     #[rustc_const_stable(feature = "futures_api", since = "1.36.0")]
162     pub const fn new(
163         clone: unsafe fn(*const ()) -> RawWaker,
164         wake: unsafe fn(*const ()),
165         wake_by_ref: unsafe fn(*const ()),
166         drop: unsafe fn(*const ()),
167     ) -> Self {
168         Self { clone, wake, wake_by_ref, drop }
169     }
170 }
171
172 /// The context of an asynchronous task.
173 ///
174 /// Currently, `Context` only serves to provide access to a [`&Waker`](Waker)
175 /// which can be used to wake the current task.
176 #[stable(feature = "futures_api", since = "1.36.0")]
177 pub struct Context<'a> {
178     waker: &'a Waker,
179     // Ensure we future-proof against variance changes by forcing
180     // the lifetime to be invariant (argument-position lifetimes
181     // are contravariant while return-position lifetimes are
182     // covariant).
183     _marker: PhantomData<fn(&'a ()) -> &'a ()>,
184 }
185
186 impl<'a> Context<'a> {
187     /// Create a new `Context` from a [`&Waker`](Waker).
188     #[stable(feature = "futures_api", since = "1.36.0")]
189     #[rustc_const_unstable(feature = "const_waker", issue = "102012")]
190     #[must_use]
191     #[inline]
192     pub const fn from_waker(waker: &'a Waker) -> Self {
193         Context { waker, _marker: PhantomData }
194     }
195
196     /// Returns a reference to the [`Waker`] for the current task.
197     #[stable(feature = "futures_api", since = "1.36.0")]
198     #[rustc_const_unstable(feature = "const_waker", issue = "102012")]
199     #[must_use]
200     #[inline]
201     pub const fn waker(&self) -> &'a Waker {
202         &self.waker
203     }
204 }
205
206 #[stable(feature = "futures_api", since = "1.36.0")]
207 impl fmt::Debug for Context<'_> {
208     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209         f.debug_struct("Context").field("waker", &self.waker).finish()
210     }
211 }
212
213 /// A `Waker` is a handle for waking up a task by notifying its executor that it
214 /// is ready to be run.
215 ///
216 /// This handle encapsulates a [`RawWaker`] instance, which defines the
217 /// executor-specific wakeup behavior.
218 ///
219 /// The typical life of a `Waker` is that it is constructed by an executor, wrapped in a
220 /// [`Context`], then passed to [`Future::poll()`]. Then, if the future chooses to return
221 /// [`Poll::Pending`], it must also store the waker somehow and call [`Waker::wake()`] when
222 /// the future should be polled again.
223 ///
224 /// Implements [`Clone`], [`Send`], and [`Sync`]; therefore, a waker may be invoked
225 /// from any thread, including ones not in any way managed by the executor. For example,
226 /// this might be done to wake a future when a blocking function call completes on another
227 /// thread.
228 ///
229 /// [`Future::poll()`]: core::future::Future::poll
230 /// [`Poll::Pending`]: core::task::Poll::Pending
231 #[repr(transparent)]
232 #[stable(feature = "futures_api", since = "1.36.0")]
233 pub struct Waker {
234     waker: RawWaker,
235 }
236
237 #[stable(feature = "futures_api", since = "1.36.0")]
238 impl Unpin for Waker {}
239 #[stable(feature = "futures_api", since = "1.36.0")]
240 unsafe impl Send for Waker {}
241 #[stable(feature = "futures_api", since = "1.36.0")]
242 unsafe impl Sync for Waker {}
243
244 impl Waker {
245     /// Wake up the task associated with this `Waker`.
246     ///
247     /// As long as the executor keeps running and the task is not finished, it is
248     /// guaranteed that each invocation of [`wake()`](Self::wake) (or
249     /// [`wake_by_ref()`](Self::wake_by_ref)) will be followed by at least one
250     /// [`poll()`] of the task to which this `Waker` belongs. This makes
251     /// it possible to temporarily yield to other tasks while running potentially
252     /// unbounded processing loops.
253     ///
254     /// Note that the above implies that multiple wake-ups may be coalesced into a
255     /// single [`poll()`] invocation by the runtime.
256     ///
257     /// Also note that yielding to competing tasks is not guaranteed: it is the
258     /// executor’s choice which task to run and the executor may choose to run the
259     /// current task again.
260     ///
261     /// [`poll()`]: crate::future::Future::poll
262     #[inline]
263     #[stable(feature = "futures_api", since = "1.36.0")]
264     pub fn wake(self) {
265         // The actual wakeup call is delegated through a virtual function call
266         // to the implementation which is defined by the executor.
267         let wake = self.waker.vtable.wake;
268         let data = self.waker.data;
269
270         // Don't call `drop` -- the waker will be consumed by `wake`.
271         crate::mem::forget(self);
272
273         // SAFETY: This is safe because `Waker::from_raw` is the only way
274         // to initialize `wake` and `data` requiring the user to acknowledge
275         // that the contract of `RawWaker` is upheld.
276         unsafe { (wake)(data) };
277     }
278
279     /// Wake up the task associated with this `Waker` without consuming the `Waker`.
280     ///
281     /// This is similar to [`wake()`](Self::wake), but may be slightly less efficient in
282     /// the case where an owned `Waker` is available. This method should be preferred to
283     /// calling `waker.clone().wake()`.
284     #[inline]
285     #[stable(feature = "futures_api", since = "1.36.0")]
286     pub fn wake_by_ref(&self) {
287         // The actual wakeup call is delegated through a virtual function call
288         // to the implementation which is defined by the executor.
289
290         // SAFETY: see `wake`
291         unsafe { (self.waker.vtable.wake_by_ref)(self.waker.data) }
292     }
293
294     /// Returns `true` if this `Waker` and another `Waker` would awake the same task.
295     ///
296     /// This function works on a best-effort basis, and may return false even
297     /// when the `Waker`s would awaken the same task. However, if this function
298     /// returns `true`, it is guaranteed that the `Waker`s will awaken the same task.
299     ///
300     /// This function is primarily used for optimization purposes.
301     #[inline]
302     #[must_use]
303     #[stable(feature = "futures_api", since = "1.36.0")]
304     pub fn will_wake(&self, other: &Waker) -> bool {
305         self.waker == other.waker
306     }
307
308     /// Creates a new `Waker` from [`RawWaker`].
309     ///
310     /// The behavior of the returned `Waker` is undefined if the contract defined
311     /// in [`RawWaker`]'s and [`RawWakerVTable`]'s documentation is not upheld.
312     /// Therefore this method is unsafe.
313     #[inline]
314     #[must_use]
315     #[stable(feature = "futures_api", since = "1.36.0")]
316     #[rustc_const_unstable(feature = "const_waker", issue = "102012")]
317     pub const unsafe fn from_raw(waker: RawWaker) -> Waker {
318         Waker { waker }
319     }
320
321     /// Get a reference to the underlying [`RawWaker`].
322     #[inline]
323     #[must_use]
324     #[unstable(feature = "waker_getters", issue = "87021")]
325     pub fn as_raw(&self) -> &RawWaker {
326         &self.waker
327     }
328 }
329
330 #[stable(feature = "futures_api", since = "1.36.0")]
331 impl Clone for Waker {
332     #[inline]
333     fn clone(&self) -> Self {
334         Waker {
335             // SAFETY: This is safe because `Waker::from_raw` is the only way
336             // to initialize `clone` and `data` requiring the user to acknowledge
337             // that the contract of [`RawWaker`] is upheld.
338             waker: unsafe { (self.waker.vtable.clone)(self.waker.data) },
339         }
340     }
341 }
342
343 #[stable(feature = "futures_api", since = "1.36.0")]
344 impl Drop for Waker {
345     #[inline]
346     fn drop(&mut self) {
347         // SAFETY: This is safe because `Waker::from_raw` is the only way
348         // to initialize `drop` and `data` requiring the user to acknowledge
349         // that the contract of `RawWaker` is upheld.
350         unsafe { (self.waker.vtable.drop)(self.waker.data) }
351     }
352 }
353
354 #[stable(feature = "futures_api", since = "1.36.0")]
355 impl fmt::Debug for Waker {
356     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
357         let vtable_ptr = self.waker.vtable as *const RawWakerVTable;
358         f.debug_struct("Waker")
359             .field("data", &self.waker.data)
360             .field("vtable", &vtable_ptr)
361             .finish()
362     }
363 }