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")]
90pub trait Wake {
91 /// Wake this task.
92 #[stable(feature = "wake_trait", since = "1.51.0")]
93 fn wake(self: Arc<Self>);
94
95 /// Wake this task without consuming the waker.
96 ///
97 /// If an executor supports a cheaper way to wake without consuming the
98 /// waker, it should override this method. By default, it clones the
99 /// [`Arc`] and calls [`wake`] on the clone.
100 ///
101 /// [`wake`]: Wake::wake
102 #[stable(feature = "wake_trait", since = "1.51.0")]
103 fn wake_by_ref(self: &Arc<Self>) {
104 self.clone().wake();
105 }
106}
107#[cfg(target_has_atomic = "ptr")]
108#[stable(feature = "wake_trait", since = "1.51.0")]
109impl<W: Wake + Send + Sync + 'static> From<Arc<W>> for Waker {
110 /// Use a [`Wake`]-able type as a `Waker`.
111 ///
112 /// No heap allocations or atomic operations are used for this conversion.
113 fn from(waker: Arc<W>) -> Waker {
114 // SAFETY: This is safe because raw_waker safely constructs
115 // a RawWaker from Arc<W>.
116 unsafe { Waker::from_raw(raw_waker(waker)) }
117 }
118}
119#[cfg(target_has_atomic = "ptr")]
120#[stable(feature = "wake_trait", since = "1.51.0")]
121impl<W: Wake + Send + Sync + 'static> From<Arc<W>> for RawWaker {
122 /// Use a `Wake`-able type as a `RawWaker`.
123 ///
124 /// No heap allocations or atomic operations are used for this conversion.
125 fn from(waker: Arc<W>) -> RawWaker {
126 raw_waker(waker)
127 }
128}
129
130/// Converts a closure into a [`Waker`].
131///
132/// The closure gets called every time the waker is woken.
133///
134/// # Examples
135///
136/// ```
137/// #![feature(waker_fn)]
138/// use std::task::waker_fn;
139///
140/// let waker = waker_fn(|| println!("woken"));
141///
142/// waker.wake_by_ref(); // Prints "woken".
143/// waker.wake(); // Prints "woken".
144/// ```
145#[cfg(target_has_atomic = "ptr")]
146#[unstable(feature = "waker_fn", issue = "149580")]
147pub fn waker_fn<F: Fn() + Send + Sync + 'static>(f: F) -> Waker {
148 struct WakeFn<F> {
149 f: F,
150 }
151
152 impl<F> Wake for WakeFn<F>
153 where
154 F: Fn(),
155 {
156 fn wake(self: Arc<Self>) {
157 (self.f)()
158 }
159
160 fn wake_by_ref(self: &Arc<Self>) {
161 (self.f)()
162 }
163 }
164
165 Waker::from(Arc::new(WakeFn { f }))
166}
167
168// NB: This private function for constructing a RawWaker is used, rather than
169// inlining this into the `From<Arc<W>> for RawWaker` impl, to ensure that
170// the safety of `From<Arc<W>> for Waker` does not depend on the correct
171// trait dispatch - instead both impls call this function directly and
172// explicitly.
173#[cfg(target_has_atomic = "ptr")]
174#[inline(always)]
175fn raw_waker<W: Wake + Send + Sync + 'static>(waker: Arc<W>) -> RawWaker {
176 // Increment the reference count of the arc to clone it.
177 //
178 // The #[inline(always)] is to ensure that raw_waker and clone_waker are
179 // always generated in the same code generation unit as one another, and
180 // therefore that the structurally identical const-promoted RawWakerVTable
181 // within both functions is deduplicated at LLVM IR code generation time.
182 // This allows optimizing Waker::will_wake to a single pointer comparison of
183 // the vtable pointers, rather than comparing all four function pointers
184 // within the vtables.
185 #[inline(always)]
186 unsafe fn clone_waker<W: Wake + Send + Sync + 'static>(waker: *const ()) -> RawWaker {
187 unsafe { Arc::increment_strong_count(waker as *const W) };
188 RawWaker::new(
189 waker,
190 &RawWakerVTable::new(clone_waker::<W>, wake::<W>, wake_by_ref::<W>, drop_waker::<W>),
191 )
192 }
193
194 // Wake by value, moving the Arc into the Wake::wake function
195 unsafe fn wake<W: Wake + Send + Sync + 'static>(waker: *const ()) {
196 let waker = unsafe { Arc::from_raw(waker as *const W) };
197 <W as Wake>::wake(waker);
198 }
199
200 // Wake by reference, wrap the waker in ManuallyDrop to avoid dropping it
201 unsafe fn wake_by_ref<W: Wake + Send + Sync + 'static>(waker: *const ()) {
202 let waker = unsafe { ManuallyDrop::new(Arc::from_raw(waker as *const W)) };
203 <W as Wake>::wake_by_ref(&waker);
204 }
205
206 // Decrement the reference count of the Arc on drop
207 unsafe fn drop_waker<W: Wake + Send + Sync + 'static>(waker: *const ()) {
208 unsafe { Arc::decrement_strong_count(waker as *const W) };
209 }
210
211 RawWaker::new(
212 Arc::into_raw(waker) as *const (),
213 &RawWakerVTable::new(clone_waker::<W>, wake::<W>, wake_by_ref::<W>, drop_waker::<W>),
214 )
215}
216
217/// An analogous trait to `Wake` but used to construct a `LocalWaker`.
218///
219/// This API works in exactly the same way as `Wake`,
220/// except that it uses an `Rc` instead of an `Arc`,
221/// and the result is a `LocalWaker` instead of a `Waker`.
222///
223/// The benefits of using `LocalWaker` over `Waker` are that it allows the local waker
224/// to hold data that does not implement `Send` and `Sync`. Additionally, it saves calls
225/// to `Arc::clone`, which requires atomic synchronization.
226///
227///
228/// # Examples
229///
230/// This is a simplified example of a `spawn` and a `block_on` function. The `spawn` function
231/// is used to push new tasks onto the run queue, while the block on function will remove them
232/// and poll them. When a task is woken, it will put itself back on the run queue to be polled
233/// by the executor.
234///
235/// **Note:** This example trades correctness for simplicity. A real world example would interleave
236/// poll calls with calls to an io reactor to wait for events instead of spinning on a loop.
237///
238/// ```rust
239/// #![feature(local_waker)]
240/// use std::task::{LocalWake, ContextBuilder, LocalWaker, Waker};
241/// use std::future::Future;
242/// use std::pin::Pin;
243/// use std::rc::Rc;
244/// use std::cell::RefCell;
245/// use std::collections::VecDeque;
246///
247///
248/// thread_local! {
249/// // A queue containing all tasks ready to do progress
250/// static RUN_QUEUE: RefCell<VecDeque<Rc<Task>>> = RefCell::default();
251/// }
252///
253/// type BoxedFuture = Pin<Box<dyn Future<Output = ()>>>;
254///
255/// struct Task(RefCell<BoxedFuture>);
256///
257/// impl LocalWake for Task {
258/// fn wake(self: Rc<Self>) {
259/// RUN_QUEUE.with_borrow_mut(|queue| {
260/// queue.push_back(self)
261/// })
262/// }
263/// }
264///
265/// fn spawn<F>(future: F)
266/// where
267/// F: Future<Output=()> + 'static + Send + Sync
268/// {
269/// let task = RefCell::new(Box::pin(future));
270/// RUN_QUEUE.with_borrow_mut(|queue| {
271/// queue.push_back(Rc::new(Task(task)));
272/// });
273/// }
274///
275/// fn block_on<F>(future: F)
276/// where
277/// F: Future<Output=()> + 'static + Sync + Send
278/// {
279/// spawn(future);
280/// loop {
281/// let Some(task) = RUN_QUEUE.with_borrow_mut(|queue| queue.pop_front()) else {
282/// // we exit, since there are no more tasks remaining on the queue
283/// return;
284/// };
285///
286/// // cast the Rc<Task> into a `LocalWaker`
287/// let local_waker: LocalWaker = task.clone().into();
288/// // Build the context using `ContextBuilder`
289/// let mut cx = ContextBuilder::from_waker(Waker::noop())
290/// .local_waker(&local_waker)
291/// .build();
292///
293/// // Poll the task
294/// let _ = task.0
295/// .borrow_mut()
296/// .as_mut()
297/// .poll(&mut cx);
298/// }
299/// }
300///
301/// block_on(async {
302/// println!("hello world");
303/// });
304/// ```
305///
306#[unstable(feature = "local_waker", issue = "118959")]
307pub trait LocalWake {
308 /// Wake this task.
309 #[unstable(feature = "local_waker", issue = "118959")]
310 fn wake(self: Rc<Self>);
311
312 /// Wake this task without consuming the local waker.
313 ///
314 /// If an executor supports a cheaper way to wake without consuming the
315 /// waker, it should override this method. By default, it clones the
316 /// [`Rc`] and calls [`wake`] on the clone.
317 ///
318 /// [`wake`]: LocalWaker::wake
319 #[unstable(feature = "local_waker", issue = "118959")]
320 fn wake_by_ref(self: &Rc<Self>) {
321 self.clone().wake();
322 }
323}
324
325#[unstable(feature = "local_waker", issue = "118959")]
326impl<W: LocalWake + 'static> From<Rc<W>> for LocalWaker {
327 /// Use a `Wake`-able type as a `LocalWaker`.
328 ///
329 /// No heap allocations or atomic operations are used for this conversion.
330 fn from(waker: Rc<W>) -> LocalWaker {
331 // SAFETY: This is safe because raw_waker safely constructs
332 // a RawWaker from Rc<W>.
333 unsafe { LocalWaker::from_raw(local_raw_waker(waker)) }
334 }
335}
336#[allow(ineffective_unstable_trait_impl)]
337#[unstable(feature = "local_waker", issue = "118959")]
338impl<W: LocalWake + 'static> From<Rc<W>> for RawWaker {
339 /// Use a `Wake`-able type as a `RawWaker`.
340 ///
341 /// No heap allocations or atomic operations are used for this conversion.
342 fn from(waker: Rc<W>) -> RawWaker {
343 local_raw_waker(waker)
344 }
345}
346
347/// Converts a closure into a [`LocalWaker`].
348///
349/// The closure gets called every time the local waker is woken.
350///
351/// # Examples
352///
353/// ```
354/// #![feature(local_waker)]
355/// #![feature(waker_fn)]
356/// use std::task::local_waker_fn;
357///
358/// let waker = local_waker_fn(|| println!("woken"));
359///
360/// waker.wake_by_ref(); // Prints "woken".
361/// waker.wake(); // Prints "woken".
362/// ```
363// #[unstable(feature = "local_waker", issue = "118959")]
364#[unstable(feature = "waker_fn", issue = "149580")]
365pub fn local_waker_fn<F: Fn() + Send + Sync + 'static>(f: F) -> LocalWaker {
366 struct LocalWakeFn<F> {
367 f: F,
368 }
369
370 impl<F> LocalWake for LocalWakeFn<F>
371 where
372 F: Fn(),
373 {
374 fn wake(self: Rc<Self>) {
375 (self.f)()
376 }
377
378 fn wake_by_ref(self: &Rc<Self>) {
379 (self.f)()
380 }
381 }
382
383 LocalWaker::from(Rc::new(LocalWakeFn { f }))
384}
385
386// NB: This private function for constructing a RawWaker is used, rather than
387// inlining this into the `From<Rc<W>> for RawWaker` impl, to ensure that
388// the safety of `From<Rc<W>> for Waker` does not depend on the correct
389// trait dispatch - instead both impls call this function directly and
390// explicitly.
391#[inline(always)]
392fn local_raw_waker<W: LocalWake + 'static>(waker: Rc<W>) -> RawWaker {
393 // Increment the reference count of the Rc to clone it.
394 //
395 // Refer to the comment on raw_waker's clone_waker regarding why this is
396 // always inline.
397 #[inline(always)]
398 unsafe fn clone_waker<W: LocalWake + 'static>(waker: *const ()) -> RawWaker {
399 unsafe { Rc::increment_strong_count(waker as *const W) };
400 RawWaker::new(
401 waker,
402 &RawWakerVTable::new(clone_waker::<W>, wake::<W>, wake_by_ref::<W>, drop_waker::<W>),
403 )
404 }
405
406 // Wake by value, moving the Rc into the LocalWake::wake function
407 unsafe fn wake<W: LocalWake + 'static>(waker: *const ()) {
408 let waker = unsafe { Rc::from_raw(waker as *const W) };
409 <W as LocalWake>::wake(waker);
410 }
411
412 // Wake by reference, wrap the waker in ManuallyDrop to avoid dropping it
413 unsafe fn wake_by_ref<W: LocalWake + 'static>(waker: *const ()) {
414 let waker = unsafe { ManuallyDrop::new(Rc::from_raw(waker as *const W)) };
415 <W as LocalWake>::wake_by_ref(&waker);
416 }
417
418 // Decrement the reference count of the Rc on drop
419 unsafe fn drop_waker<W: LocalWake + 'static>(waker: *const ()) {
420 unsafe { Rc::decrement_strong_count(waker as *const W) };
421 }
422
423 RawWaker::new(
424 Rc::into_raw(waker) as *const (),
425 &RawWakerVTable::new(clone_waker::<W>, wake::<W>, wake_by_ref::<W>, drop_waker::<W>),
426 )
427}