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