Skip to main content

alloc/
task.rs

1#![stable(feature = "wake_trait", since = "1.51.0")]
2
3//! Types and Traits for working with asynchronous tasks.
4//!
5//! **Note**: Some of the types in this module are only available
6//! on platforms that support atomic loads and stores of pointers.
7//! This may be detected at compile time using
8//! `#[cfg(target_has_atomic = "ptr")]`.
9
10use core::mem::ManuallyDrop;
11#[cfg(target_has_atomic = "ptr")]
12use core::task::Waker;
13use core::task::{LocalWaker, RawWaker, RawWakerVTable};
14
15use crate::rc::Rc;
16#[cfg(target_has_atomic = "ptr")]
17use crate::sync::Arc;
18
19/// The implementation of waking a task on an executor.
20///
21/// This trait can be used to create a [`Waker`]. An executor can define an
22/// implementation of this trait, and use that to construct a [`Waker`] to pass
23/// to the tasks that are executed on that executor.
24///
25/// This trait is a memory-safe and ergonomic alternative to constructing a
26/// [`RawWaker`]. It supports the common executor design in which the data used
27/// to wake up a task is stored in an [`Arc`]. Some executors (especially
28/// those for embedded systems) cannot use this API, which is why [`RawWaker`]
29/// exists as an alternative for those systems.
30///
31/// To construct a [`Waker`] from some type `W` implementing this trait,
32/// wrap it in an [`Arc<W>`](Arc) and call `Waker::from()` on that.
33/// It is also possible to convert to [`RawWaker`] in the same way.
34///
35/// <!-- Ideally we'd link to the `From` impl, but rustdoc doesn't generate any page for it within
36///      `alloc` because `alloc` neither defines nor re-exports `From` or `Waker`, and we can't
37///      link ../../std/task/struct.Waker.html#impl-From%3CArc%3CW,+Global%3E%3E-for-Waker
38///      without getting a link-checking error in CI. -->
39///
40/// # Examples
41///
42/// A basic `block_on` function that takes a future and runs it to completion on
43/// the current thread.
44///
45/// **Note:** This example trades correctness for simplicity. In order to prevent
46/// deadlocks, production-grade implementations will also need to handle
47/// intermediate calls to `thread::unpark` as well as nested invocations.
48///
49/// ```rust
50/// use std::future::Future;
51/// use std::sync::Arc;
52/// use std::task::{Context, Poll, Wake};
53/// use std::thread::{self, Thread};
54/// use core::pin::pin;
55///
56/// /// A waker that wakes up the current thread when called.
57/// struct ThreadWaker(Thread);
58///
59/// impl Wake for ThreadWaker {
60///     fn wake(self: Arc<Self>) {
61///         self.0.unpark();
62///     }
63/// }
64///
65/// /// Run a future to completion on the current thread.
66/// fn block_on<T>(fut: impl Future<Output = T>) -> T {
67///     // Pin the future so it can be polled.
68///     let mut fut = pin!(fut);
69///
70///     // Create a new context to be passed to the future.
71///     let t = thread::current();
72///     let waker = Arc::new(ThreadWaker(t)).into();
73///     let mut cx = Context::from_waker(&waker);
74///
75///     // Run the future to completion.
76///     loop {
77///         match fut.as_mut().poll(&mut cx) {
78///             Poll::Ready(res) => return res,
79///             Poll::Pending => thread::park(),
80///         }
81///     }
82/// }
83///
84/// block_on(async {
85///     println!("Hi from inside a future!");
86/// });
87/// ```
88#[cfg(target_has_atomic = "ptr")]
89#[stable(feature = "wake_trait", since = "1.51.0")]
90#[rustc_diagnostic_item = "Wake"]
91pub trait Wake {
92    /// Wake this task.
93    #[stable(feature = "wake_trait", since = "1.51.0")]
94    fn wake(self: Arc<Self>);
95
96    /// Wake this task without consuming the waker.
97    ///
98    /// If an executor supports a cheaper way to wake without consuming the
99    /// waker, it should override this method. By default, it clones the
100    /// [`Arc`] and calls [`wake`] on the clone.
101    ///
102    /// [`wake`]: Wake::wake
103    #[stable(feature = "wake_trait", since = "1.51.0")]
104    fn wake_by_ref(self: &Arc<Self>) {
105        self.clone().wake();
106    }
107}
108#[cfg(target_has_atomic = "ptr")]
109#[stable(feature = "wake_trait", since = "1.51.0")]
110impl<W: Wake + Send + Sync + 'static> From<Arc<W>> for Waker {
111    /// Use a [`Wake`]-able type as a `Waker`.
112    ///
113    /// No heap allocations or atomic operations are used for this conversion.
114    fn from(waker: Arc<W>) -> Waker {
115        // SAFETY: This is safe because raw_waker safely constructs
116        // a RawWaker from Arc<W>.
117        unsafe { Waker::from_raw(raw_waker(waker)) }
118    }
119}
120#[cfg(target_has_atomic = "ptr")]
121#[stable(feature = "wake_trait", since = "1.51.0")]
122impl<W: Wake + Send + Sync + 'static> From<Arc<W>> for RawWaker {
123    /// Use a `Wake`-able type as a `RawWaker`.
124    ///
125    /// No heap allocations or atomic operations are used for this conversion.
126    fn from(waker: Arc<W>) -> RawWaker {
127        raw_waker(waker)
128    }
129}
130
131/// Converts a closure into a [`Waker`].
132///
133/// The closure gets called every time the waker is woken.
134///
135/// # Examples
136///
137/// ```
138/// #![feature(waker_fn)]
139/// use std::task::waker_fn;
140///
141/// let waker = waker_fn(|| println!("woken"));
142///
143/// waker.wake_by_ref(); // Prints "woken".
144/// waker.wake();        // Prints "woken".
145/// ```
146#[cfg(target_has_atomic = "ptr")]
147#[unstable(feature = "waker_fn", issue = "149580")]
148pub fn waker_fn<F: Fn() + Send + Sync + 'static>(f: F) -> Waker {
149    struct WakeFn<F> {
150        f: F,
151    }
152
153    impl<F> Wake for WakeFn<F>
154    where
155        F: Fn(),
156    {
157        fn wake(self: Arc<Self>) {
158            (self.f)()
159        }
160
161        fn wake_by_ref(self: &Arc<Self>) {
162            (self.f)()
163        }
164    }
165
166    Waker::from(Arc::new(WakeFn { f }))
167}
168
169// NB: This private function for constructing a RawWaker is used, rather than
170// inlining this into the `From<Arc<W>> for RawWaker` impl, to ensure that
171// the safety of `From<Arc<W>> for Waker` does not depend on the correct
172// trait dispatch - instead both impls call this function directly and
173// explicitly.
174#[cfg(target_has_atomic = "ptr")]
175#[inline(always)]
176fn raw_waker<W: Wake + Send + Sync + 'static>(waker: Arc<W>) -> RawWaker {
177    // Increment the reference count of the arc to clone it.
178    //
179    // The #[inline(always)] is to ensure that raw_waker and clone_waker are
180    // always generated in the same code generation unit as one another, and
181    // therefore that the structurally identical const-promoted RawWakerVTable
182    // within both functions is deduplicated at LLVM IR code generation time.
183    // This allows optimizing Waker::will_wake to a single pointer comparison of
184    // the vtable pointers, rather than comparing all four function pointers
185    // within the vtables.
186    #[inline(always)]
187    unsafe fn clone_waker<W: Wake + Send + Sync + 'static>(waker: *const ()) -> RawWaker {
188        unsafe { Arc::increment_strong_count(waker as *const W) };
189        RawWaker::new(
190            waker,
191            &RawWakerVTable::new(clone_waker::<W>, wake::<W>, wake_by_ref::<W>, drop_waker::<W>),
192        )
193    }
194
195    // Wake by value, moving the Arc into the Wake::wake function
196    unsafe fn wake<W: Wake + Send + Sync + 'static>(waker: *const ()) {
197        let waker = unsafe { Arc::from_raw(waker as *const W) };
198        <W as Wake>::wake(waker);
199    }
200
201    // Wake by reference, wrap the waker in ManuallyDrop to avoid dropping it
202    unsafe fn wake_by_ref<W: Wake + Send + Sync + 'static>(waker: *const ()) {
203        let waker = unsafe { ManuallyDrop::new(Arc::from_raw(waker as *const W)) };
204        <W as Wake>::wake_by_ref(&waker);
205    }
206
207    // Decrement the reference count of the Arc on drop
208    unsafe fn drop_waker<W: Wake + Send + Sync + 'static>(waker: *const ()) {
209        unsafe { Arc::decrement_strong_count(waker as *const W) };
210    }
211
212    RawWaker::new(
213        Arc::into_raw(waker) as *const (),
214        &RawWakerVTable::new(clone_waker::<W>, wake::<W>, wake_by_ref::<W>, drop_waker::<W>),
215    )
216}
217
218/// An analogous trait to `Wake` but used to construct a `LocalWaker`.
219///
220/// This API works in exactly the same way as `Wake`,
221/// except that it uses an `Rc` instead of an `Arc`,
222/// and the result is a `LocalWaker` instead of a `Waker`.
223///
224/// The benefits of using `LocalWaker` over `Waker` are that it allows the local waker
225/// to hold data that does not implement `Send` and `Sync`. Additionally, it saves calls
226/// to `Arc::clone`, which requires atomic synchronization.
227///
228///
229/// # Examples
230///
231/// This is a simplified example of a `spawn` and a `block_on` function. The `spawn` function
232/// is used to push new tasks onto the run queue, while the block on function will remove them
233/// and poll them. When a task is woken, it will put itself back on the run queue to be polled
234/// by the executor.
235///
236/// **Note:** This example trades correctness for simplicity. A real world example would interleave
237/// poll calls with calls to an io reactor to wait for events instead of spinning on a loop.
238///
239/// ```rust
240/// #![feature(local_waker)]
241/// use std::task::{LocalWake, ContextBuilder, LocalWaker, Waker};
242/// use std::future::Future;
243/// use std::pin::Pin;
244/// use std::rc::Rc;
245/// use std::cell::RefCell;
246/// use std::collections::VecDeque;
247///
248///
249/// thread_local! {
250///     // A queue containing all tasks ready to do progress
251///     static RUN_QUEUE: RefCell<VecDeque<Rc<Task>>> = RefCell::default();
252/// }
253///
254/// type BoxedFuture = Pin<Box<dyn Future<Output = ()>>>;
255///
256/// struct Task(RefCell<BoxedFuture>);
257///
258/// impl LocalWake for Task {
259///     fn wake(self: Rc<Self>) {
260///         RUN_QUEUE.with_borrow_mut(|queue| {
261///             queue.push_back(self)
262///         })
263///     }
264/// }
265///
266/// fn spawn<F>(future: F)
267/// where
268///     F: Future<Output=()> + 'static + Send + Sync
269/// {
270///     let task = RefCell::new(Box::pin(future));
271///     RUN_QUEUE.with_borrow_mut(|queue| {
272///         queue.push_back(Rc::new(Task(task)));
273///     });
274/// }
275///
276/// fn block_on<F>(future: F)
277/// where
278///     F: Future<Output=()> + 'static + Sync + Send
279/// {
280///     spawn(future);
281///     loop {
282///         let Some(task) = RUN_QUEUE.with_borrow_mut(|queue| queue.pop_front()) else {
283///             // we exit, since there are no more tasks remaining on the queue
284///             return;
285///         };
286///
287///         // cast the Rc<Task> into a `LocalWaker`
288///         let local_waker: LocalWaker = task.clone().into();
289///         // Build the context using `ContextBuilder`
290///         let mut cx = ContextBuilder::from_waker(Waker::noop())
291///             .local_waker(&local_waker)
292///             .build();
293///
294///         // Poll the task
295///         let _ = task.0
296///             .borrow_mut()
297///             .as_mut()
298///             .poll(&mut cx);
299///     }
300/// }
301///
302/// block_on(async {
303///     println!("hello world");
304/// });
305/// ```
306///
307#[unstable(feature = "local_waker", issue = "118959")]
308pub trait LocalWake {
309    /// Wake this task.
310    #[unstable(feature = "local_waker", issue = "118959")]
311    fn wake(self: Rc<Self>);
312
313    /// Wake this task without consuming the local waker.
314    ///
315    /// If an executor supports a cheaper way to wake without consuming the
316    /// waker, it should override this method. By default, it clones the
317    /// [`Rc`] and calls [`wake`] on the clone.
318    ///
319    /// [`wake`]: LocalWaker::wake
320    #[unstable(feature = "local_waker", issue = "118959")]
321    fn wake_by_ref(self: &Rc<Self>) {
322        self.clone().wake();
323    }
324}
325
326#[unstable(feature = "local_waker", issue = "118959")]
327impl<W: LocalWake + 'static> From<Rc<W>> for LocalWaker {
328    /// Use a `Wake`-able type as a `LocalWaker`.
329    ///
330    /// No heap allocations or atomic operations are used for this conversion.
331    fn from(waker: Rc<W>) -> LocalWaker {
332        // SAFETY: This is safe because raw_waker safely constructs
333        // a RawWaker from Rc<W>.
334        unsafe { LocalWaker::from_raw(local_raw_waker(waker)) }
335    }
336}
337#[allow(ineffective_unstable_trait_impl)]
338#[unstable(feature = "local_waker", issue = "118959")]
339impl<W: LocalWake + 'static> From<Rc<W>> for RawWaker {
340    /// Use a `Wake`-able type as a `RawWaker`.
341    ///
342    /// No heap allocations or atomic operations are used for this conversion.
343    fn from(waker: Rc<W>) -> RawWaker {
344        local_raw_waker(waker)
345    }
346}
347
348/// Converts a closure into a [`LocalWaker`].
349///
350/// The closure gets called every time the local waker is woken.
351///
352/// # Examples
353///
354/// ```
355/// #![feature(local_waker)]
356/// #![feature(waker_fn)]
357/// use std::task::local_waker_fn;
358///
359/// let waker = local_waker_fn(|| println!("woken"));
360///
361/// waker.wake_by_ref(); // Prints "woken".
362/// waker.wake();        // Prints "woken".
363/// ```
364// #[unstable(feature = "local_waker", issue = "118959")]
365#[unstable(feature = "waker_fn", issue = "149580")]
366pub fn local_waker_fn<F: Fn() + Send + Sync + 'static>(f: F) -> LocalWaker {
367    struct LocalWakeFn<F> {
368        f: F,
369    }
370
371    impl<F> LocalWake for LocalWakeFn<F>
372    where
373        F: Fn(),
374    {
375        fn wake(self: Rc<Self>) {
376            (self.f)()
377        }
378
379        fn wake_by_ref(self: &Rc<Self>) {
380            (self.f)()
381        }
382    }
383
384    LocalWaker::from(Rc::new(LocalWakeFn { f }))
385}
386
387// NB: This private function for constructing a RawWaker is used, rather than
388// inlining this into the `From<Rc<W>> for RawWaker` impl, to ensure that
389// the safety of `From<Rc<W>> for Waker` does not depend on the correct
390// trait dispatch - instead both impls call this function directly and
391// explicitly.
392#[inline(always)]
393fn local_raw_waker<W: LocalWake + 'static>(waker: Rc<W>) -> RawWaker {
394    // Increment the reference count of the Rc to clone it.
395    //
396    // Refer to the comment on raw_waker's clone_waker regarding why this is
397    // always inline.
398    #[inline(always)]
399    unsafe fn clone_waker<W: LocalWake + 'static>(waker: *const ()) -> RawWaker {
400        unsafe { Rc::increment_strong_count(waker as *const W) };
401        RawWaker::new(
402            waker,
403            &RawWakerVTable::new(clone_waker::<W>, wake::<W>, wake_by_ref::<W>, drop_waker::<W>),
404        )
405    }
406
407    // Wake by value, moving the Rc into the LocalWake::wake function
408    unsafe fn wake<W: LocalWake + 'static>(waker: *const ()) {
409        let waker = unsafe { Rc::from_raw(waker as *const W) };
410        <W as LocalWake>::wake(waker);
411    }
412
413    // Wake by reference, wrap the waker in ManuallyDrop to avoid dropping it
414    unsafe fn wake_by_ref<W: LocalWake + 'static>(waker: *const ()) {
415        let waker = unsafe { ManuallyDrop::new(Rc::from_raw(waker as *const W)) };
416        <W as LocalWake>::wake_by_ref(&waker);
417    }
418
419    // Decrement the reference count of the Rc on drop
420    unsafe fn drop_waker<W: LocalWake + 'static>(waker: *const ()) {
421        unsafe { Rc::decrement_strong_count(waker as *const W) };
422    }
423
424    RawWaker::new(
425        Rc::into_raw(waker) as *const (),
426        &RawWakerVTable::new(clone_waker::<W>, wake::<W>, wake_by_ref::<W>, drop_waker::<W>),
427    )
428}