1 #![stable(feature = "futures_api", since = "1.36.0")]
4 use crate::marker::{PhantomData, Unpin};
6 /// A `RawWaker` allows the implementor of a task executor to create a [`Waker`]
7 /// which provides customized wakeup behavior.
9 /// [vtable]: https://en.wikipedia.org/wiki/Virtual_method_table
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")]
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.
22 /// Virtual function pointer table that customizes the behavior of this waker.
23 vtable: &'static RawWakerVTable,
27 /// Creates a new `RawWaker` from the provided `data` pointer and `vtable`.
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.
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.
40 #[stable(feature = "futures_api", since = "1.36.0")]
41 #[rustc_const_stable(feature = "futures_api", since = "1.36.0")]
43 pub const fn new(data: *const (), vtable: &'static RawWakerVTable) -> RawWaker {
44 RawWaker { data, vtable }
47 /// Get the `data` pointer used to create this `RawWaker`.
50 #[unstable(feature = "waker_getters", issue = "87021")]
51 pub fn data(&self) -> *const () {
55 /// Get the `vtable` pointer used to create this `RawWaker`.
58 #[unstable(feature = "waker_getters", issue = "87021")]
59 pub fn vtable(&self) -> &'static RawWakerVTable {
64 /// A virtual function pointer table (vtable) that specifies the behavior
65 /// of a [`RawWaker`].
67 /// The pointer passed to all functions inside the vtable is the `data` pointer
68 /// from the enclosing [`RawWaker`] object.
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.
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.
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,
92 /// This function will be called when `wake` is called on the [`Waker`].
93 /// It must wake up the task associated with this [`RawWaker`].
95 /// The implementation of this function must make sure to release any
96 /// resources that are associated with this instance of a [`RawWaker`] and
98 wake: unsafe fn(*const ()),
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`].
103 /// This function is similar to `wake`, but must not consume the provided data
105 wake_by_ref: unsafe fn(*const ()),
107 /// This function gets called when a [`Waker`] gets dropped.
109 /// The implementation of this function must make sure to release any
110 /// resources that are associated with this instance of a [`RawWaker`] and
112 drop: unsafe fn(*const ()),
115 impl RawWakerVTable {
116 /// Creates a new `RawWakerVTable` from the provided `clone`, `wake`,
117 /// `wake_by_ref`, and `drop` functions.
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.
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.
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`].
137 /// This function will be called when `wake` is called on the [`Waker`].
138 /// It must wake up the task associated with this [`RawWaker`].
140 /// The implementation of this function must make sure to release any
141 /// resources that are associated with this instance of a [`RawWaker`] and
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`].
149 /// This function is similar to `wake`, but must not consume the provided data
154 /// This function gets called when a [`Waker`] gets dropped.
156 /// The implementation of this function must make sure to release any
157 /// resources that are associated with this instance of a [`RawWaker`] and
160 #[stable(feature = "futures_api", since = "1.36.0")]
161 #[rustc_const_stable(feature = "futures_api", since = "1.36.0")]
163 clone: unsafe fn(*const ()) -> RawWaker,
164 wake: unsafe fn(*const ()),
165 wake_by_ref: unsafe fn(*const ()),
166 drop: unsafe fn(*const ()),
168 Self { clone, wake, wake_by_ref, drop }
172 /// The context of an asynchronous task.
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> {
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
183 _marker: PhantomData<fn(&'a ()) -> &'a ()>,
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")]
192 pub const fn from_waker(waker: &'a Waker) -> Self {
193 Context { waker, _marker: PhantomData }
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")]
201 pub const fn waker(&self) -> &'a Waker {
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()
213 /// A `Waker` is a handle for waking up a task by notifying its executor that it
214 /// is ready to be run.
216 /// This handle encapsulates a [`RawWaker`] instance, which defines the
217 /// executor-specific wakeup behavior.
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.
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
229 /// [`Future::poll()`]: core::future::Future::poll
230 /// [`Poll::Pending`]: core::task::Poll::Pending
232 #[stable(feature = "futures_api", since = "1.36.0")]
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 {}
245 /// Wake up the task associated with this `Waker`.
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.
254 /// Note that the above implies that multiple wake-ups may be coalesced into a
255 /// single [`poll()`] invocation by the runtime.
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.
261 /// [`poll()`]: crate::future::Future::poll
263 #[stable(feature = "futures_api", since = "1.36.0")]
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;
270 // Don't call `drop` -- the waker will be consumed by `wake`.
271 crate::mem::forget(self);
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) };
279 /// Wake up the task associated with this `Waker` without consuming the `Waker`.
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()`.
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.
290 // SAFETY: see `wake`
291 unsafe { (self.waker.vtable.wake_by_ref)(self.waker.data) }
294 /// Returns `true` if this `Waker` and another `Waker` would awake the same task.
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.
300 /// This function is primarily used for optimization purposes.
303 #[stable(feature = "futures_api", since = "1.36.0")]
304 pub fn will_wake(&self, other: &Waker) -> bool {
305 self.waker == other.waker
308 /// Creates a new `Waker` from [`RawWaker`].
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.
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 {
321 /// Get a reference to the underlying [`RawWaker`].
324 #[unstable(feature = "waker_getters", issue = "87021")]
325 pub fn as_raw(&self) -> &RawWaker {
330 #[stable(feature = "futures_api", since = "1.36.0")]
331 impl Clone for Waker {
333 fn clone(&self) -> Self {
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) },
343 #[stable(feature = "futures_api", since = "1.36.0")]
344 impl Drop for Waker {
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) }
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)