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")]
178 pub struct Context<'a> {
180 // Ensure we future-proof against variance changes by forcing
181 // the lifetime to be invariant (argument-position lifetimes
182 // are contravariant while return-position lifetimes are
184 _marker: PhantomData<fn(&'a ()) -> &'a ()>,
185 // Ensure `Context` is `!Send` and `!Sync` in order to allow
186 // for future `!Send` and / or `!Sync` fields.
187 _marker2: PhantomData<*mut ()>,
190 impl<'a> Context<'a> {
191 /// Create a new `Context` from a [`&Waker`](Waker).
192 #[stable(feature = "futures_api", since = "1.36.0")]
193 #[rustc_const_unstable(feature = "const_waker", issue = "102012")]
196 pub const fn from_waker(waker: &'a Waker) -> Self {
197 Context { waker, _marker: PhantomData, _marker2: PhantomData }
200 /// Returns a reference to the [`Waker`] for the current task.
201 #[stable(feature = "futures_api", since = "1.36.0")]
202 #[rustc_const_unstable(feature = "const_waker", issue = "102012")]
205 pub const fn waker(&self) -> &'a Waker {
210 #[stable(feature = "futures_api", since = "1.36.0")]
211 impl fmt::Debug for Context<'_> {
212 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213 f.debug_struct("Context").field("waker", &self.waker).finish()
217 /// A `Waker` is a handle for waking up a task by notifying its executor that it
218 /// is ready to be run.
220 /// This handle encapsulates a [`RawWaker`] instance, which defines the
221 /// executor-specific wakeup behavior.
223 /// The typical life of a `Waker` is that it is constructed by an executor, wrapped in a
224 /// [`Context`], then passed to [`Future::poll()`]. Then, if the future chooses to return
225 /// [`Poll::Pending`], it must also store the waker somehow and call [`Waker::wake()`] when
226 /// the future should be polled again.
228 /// Implements [`Clone`], [`Send`], and [`Sync`]; therefore, a waker may be invoked
229 /// from any thread, including ones not in any way managed by the executor. For example,
230 /// this might be done to wake a future when a blocking function call completes on another
233 /// [`Future::poll()`]: core::future::Future::poll
234 /// [`Poll::Pending`]: core::task::Poll::Pending
236 #[stable(feature = "futures_api", since = "1.36.0")]
241 #[stable(feature = "futures_api", since = "1.36.0")]
242 impl Unpin for Waker {}
243 #[stable(feature = "futures_api", since = "1.36.0")]
244 unsafe impl Send for Waker {}
245 #[stable(feature = "futures_api", since = "1.36.0")]
246 unsafe impl Sync for Waker {}
249 /// Wake up the task associated with this `Waker`.
251 /// As long as the executor keeps running and the task is not finished, it is
252 /// guaranteed that each invocation of [`wake()`](Self::wake) (or
253 /// [`wake_by_ref()`](Self::wake_by_ref)) will be followed by at least one
254 /// [`poll()`] of the task to which this `Waker` belongs. This makes
255 /// it possible to temporarily yield to other tasks while running potentially
256 /// unbounded processing loops.
258 /// Note that the above implies that multiple wake-ups may be coalesced into a
259 /// single [`poll()`] invocation by the runtime.
261 /// Also note that yielding to competing tasks is not guaranteed: it is the
262 /// executor’s choice which task to run and the executor may choose to run the
263 /// current task again.
265 /// [`poll()`]: crate::future::Future::poll
267 #[stable(feature = "futures_api", since = "1.36.0")]
269 // The actual wakeup call is delegated through a virtual function call
270 // to the implementation which is defined by the executor.
271 let wake = self.waker.vtable.wake;
272 let data = self.waker.data;
274 // Don't call `drop` -- the waker will be consumed by `wake`.
275 crate::mem::forget(self);
277 // SAFETY: This is safe because `Waker::from_raw` is the only way
278 // to initialize `wake` and `data` requiring the user to acknowledge
279 // that the contract of `RawWaker` is upheld.
280 unsafe { (wake)(data) };
283 /// Wake up the task associated with this `Waker` without consuming the `Waker`.
285 /// This is similar to [`wake()`](Self::wake), but may be slightly less efficient in
286 /// the case where an owned `Waker` is available. This method should be preferred to
287 /// calling `waker.clone().wake()`.
289 #[stable(feature = "futures_api", since = "1.36.0")]
290 pub fn wake_by_ref(&self) {
291 // The actual wakeup call is delegated through a virtual function call
292 // to the implementation which is defined by the executor.
294 // SAFETY: see `wake`
295 unsafe { (self.waker.vtable.wake_by_ref)(self.waker.data) }
298 /// Returns `true` if this `Waker` and another `Waker` would awake the same task.
300 /// This function works on a best-effort basis, and may return false even
301 /// when the `Waker`s would awaken the same task. However, if this function
302 /// returns `true`, it is guaranteed that the `Waker`s will awaken the same task.
304 /// This function is primarily used for optimization purposes.
307 #[stable(feature = "futures_api", since = "1.36.0")]
308 pub fn will_wake(&self, other: &Waker) -> bool {
309 self.waker == other.waker
312 /// Creates a new `Waker` from [`RawWaker`].
314 /// The behavior of the returned `Waker` is undefined if the contract defined
315 /// in [`RawWaker`]'s and [`RawWakerVTable`]'s documentation is not upheld.
316 /// Therefore this method is unsafe.
319 #[stable(feature = "futures_api", since = "1.36.0")]
320 #[rustc_const_unstable(feature = "const_waker", issue = "102012")]
321 pub const unsafe fn from_raw(waker: RawWaker) -> Waker {
325 /// Get a reference to the underlying [`RawWaker`].
328 #[unstable(feature = "waker_getters", issue = "87021")]
329 pub fn as_raw(&self) -> &RawWaker {
334 #[stable(feature = "futures_api", since = "1.36.0")]
335 impl Clone for Waker {
337 fn clone(&self) -> Self {
339 // SAFETY: This is safe because `Waker::from_raw` is the only way
340 // to initialize `clone` and `data` requiring the user to acknowledge
341 // that the contract of [`RawWaker`] is upheld.
342 waker: unsafe { (self.waker.vtable.clone)(self.waker.data) },
347 #[stable(feature = "futures_api", since = "1.36.0")]
348 impl Drop for Waker {
351 // SAFETY: This is safe because `Waker::from_raw` is the only way
352 // to initialize `drop` and `data` requiring the user to acknowledge
353 // that the contract of `RawWaker` is upheld.
354 unsafe { (self.waker.vtable.drop)(self.waker.data) }
358 #[stable(feature = "futures_api", since = "1.36.0")]
359 impl fmt::Debug for Waker {
360 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
361 let vtable_ptr = self.waker.vtable as *const RawWakerVTable;
362 f.debug_struct("Waker")
363 .field("data", &self.waker.data)
364 .field("vtable", &vtable_ptr)