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 unsafe { Arc::increment_strong_count(waker as *const W) };
193 RawWaker::new(
194 waker,
195 &RawWakerVTable::new(clone_waker::<W>, wake::<W>, wake_by_ref::<W>, drop_waker::<W>),
196 )
197 }
198
199 // Wake by value, moving the Arc into the Wake::wake function
200 unsafe fn wake<W: Wake + Send + Sync + 'static>(waker: *const ()) {
201 let waker = unsafe { Arc::from_raw(waker as *const W) };
202 <W as Wake>::wake(waker);
203 }
204
205 // Wake by reference, wrap the waker in ManuallyDrop to avoid dropping it
206 unsafe fn wake_by_ref<W: Wake + Send + Sync + 'static>(waker: *const ()) {
207 let waker = unsafe { ManuallyDrop::new(Arc::from_raw(waker as *const W)) };
208 <W as Wake>::wake_by_ref(&waker);
209 }
210
211 // Decrement the reference count of the Arc on drop
212 unsafe fn drop_waker<W: Wake + Send + Sync + 'static>(waker: *const ()) {
213 unsafe { Arc::decrement_strong_count(waker as *const W) };
214 }
215
216 RawWaker::new(
217 Arc::into_raw(waker) as *const (),
218 &RawWakerVTable::new(clone_waker::<W>, wake::<W>, wake_by_ref::<W>, drop_waker::<W>),
219 )
220}
221
222/// An analogous trait to `Wake` but used to construct a `LocalWaker`.
223///
224/// This API works in exactly the same way as `Wake`,
225/// except that it uses an `Rc` instead of an `Arc`,
226/// and the result is a `LocalWaker` instead of a `Waker`.
227///
228/// The benefits of using `LocalWaker` over `Waker` are that it allows the local waker
229/// to hold data that does not implement `Send` and `Sync`. Additionally, it saves calls
230/// to `Arc::clone`, which requires atomic synchronization.
231///
232///
233/// # Examples
234///
235/// This is a simplified example of a `spawn` and a `block_on` function. The `spawn` function
236/// is used to push new tasks onto the run queue, while the block on function will remove them
237/// and poll them. When a task is woken, it will put itself back on the run queue to be polled
238/// by the executor.
239///
240/// **Note:** This example trades correctness for simplicity. A real world example would interleave
241/// poll calls with calls to an io reactor to wait for events instead of spinning on a loop.
242///
243/// ```rust
244/// #![feature(local_waker)]
245/// use std::task::{LocalWake, ContextBuilder, LocalWaker, Waker};
246/// use std::future::Future;
247/// use std::pin::Pin;
248/// use std::rc::Rc;
249/// use std::cell::RefCell;
250/// use std::collections::VecDeque;
251///
252///
253/// thread_local! {
254/// // A queue containing all tasks ready to do progress
255/// static RUN_QUEUE: RefCell<VecDeque<Rc<Task>>> = RefCell::default();
256/// }
257///
258/// type BoxedFuture = Pin<Box<dyn Future<Output = ()>>>;
259///
260/// struct Task(RefCell<BoxedFuture>);
261///
262/// impl LocalWake for Task {
263/// fn wake(self: Rc<Self>) {
264/// RUN_QUEUE.with_borrow_mut(|queue| {
265/// queue.push_back(self)
266/// })
267/// }
268/// }
269///
270/// fn spawn<F>(future: F)
271/// where
272/// F: Future<Output=()> + 'static + Send + Sync
273/// {
274/// let task = RefCell::new(Box::pin(future));
275/// RUN_QUEUE.with_borrow_mut(|queue| {
276/// queue.push_back(Rc::new(Task(task)));
277/// });
278/// }
279///
280/// fn block_on<F>(future: F)
281/// where
282/// F: Future<Output=()> + 'static + Sync + Send
283/// {
284/// spawn(future);
285/// loop {
286/// let Some(task) = RUN_QUEUE.with_borrow_mut(|queue| queue.pop_front()) else {
287/// // we exit, since there are no more tasks remaining on the queue
288/// return;
289/// };
290///
291/// // cast the Rc<Task> into a `LocalWaker`
292/// let local_waker: LocalWaker = task.clone().into();
293/// // Build the context using `ContextBuilder`
294/// let mut cx = ContextBuilder::from_waker(Waker::noop())
295/// .local_waker(&local_waker)
296/// .build();
297///
298/// // Poll the task
299/// let _ = task.0
300/// .borrow_mut()
301/// .as_mut()
302/// .poll(&mut cx);
303/// }
304/// }
305///
306/// block_on(async {
307/// println!("hello world");
308/// });
309/// ```
310///
311#[unstable(feature = "local_waker", issue = "118959")]
312pub trait LocalWake {
313 /// Wake this task.
314 #[unstable(feature = "local_waker", issue = "118959")]
315 fn wake(self: Rc<Self>);
316
317 /// Wake this task without consuming the local waker.
318 ///
319 /// If an executor supports a cheaper way to wake without consuming the
320 /// waker, it should override this method. By default, it clones the
321 /// [`Rc`] and calls [`wake`] on the clone.
322 ///
323 /// [`wake`]: LocalWaker::wake
324 #[unstable(feature = "local_waker", issue = "118959")]
325 fn wake_by_ref(self: &Rc<Self>) {
326 self.clone().wake();
327 }
328}
329
330#[unstable(feature = "local_waker", issue = "118959")]
331impl<W: LocalWake + 'static> From<Rc<W>> for LocalWaker {
332 /// Use a `Wake`-able type as a `LocalWaker`.
333 ///
334 /// No heap allocations or atomic operations are used for this conversion.
335 fn from(waker: Rc<W>) -> LocalWaker {
336 // SAFETY: This is safe because raw_waker safely constructs
337 // a RawWaker from Rc<W>.
338 unsafe { LocalWaker::from_raw(local_raw_waker(waker)) }
339 }
340}
341#[allow(ineffective_unstable_trait_impl)]
342#[unstable(feature = "local_waker", issue = "118959")]
343impl<W: LocalWake + 'static> From<Rc<W>> for RawWaker {
344 /// Use a `Wake`-able type as a `RawWaker`.
345 ///
346 /// No heap allocations or atomic operations are used for this conversion.
347 fn from(waker: Rc<W>) -> RawWaker {
348 local_raw_waker(waker)
349 }
350}
351
352/// Converts a closure into a [`LocalWaker`].
353///
354/// The closure gets called every time the local waker is woken.
355///
356/// # Examples
357///
358/// ```
359/// #![feature(local_waker)]
360/// #![feature(waker_fn)]
361/// use std::task::local_waker_fn;
362///
363/// let waker = local_waker_fn(|| println!("woken"));
364///
365/// waker.wake_by_ref(); // Prints "woken".
366/// waker.wake(); // Prints "woken".
367/// ```
368// #[unstable(feature = "local_waker", issue = "118959")]
369#[unstable(feature = "waker_fn", issue = "149580")]
370pub fn local_waker_fn<F: Fn() + Send + Sync + 'static>(f: F) -> LocalWaker {
371 struct LocalWakeFn<F> {
372 f: F,
373 }
374
375 impl<F> LocalWake for LocalWakeFn<F>
376 where
377 F: Fn(),
378 {
379 fn wake(self: Rc<Self>) {
380 (self.f)()
381 }
382
383 fn wake_by_ref(self: &Rc<Self>) {
384 (self.f)()
385 }
386 }
387
388 LocalWaker::from(Rc::new(LocalWakeFn { f }))
389}
390
391// NB: This private function for constructing a RawWaker is used, rather than
392// inlining this into the `From<Rc<W>> for RawWaker` impl, to ensure that
393// the safety of `From<Rc<W>> for Waker` does not depend on the correct
394// trait dispatch - instead both impls call this function directly and
395// explicitly.
396#[inline(always)]
397fn local_raw_waker<W: LocalWake + 'static>(waker: Rc<W>) -> RawWaker {
398 // Increment the reference count of the Rc to clone it.
399 //
400 // Refer to the comment on raw_waker's clone_waker regarding why this is
401 // always inline.
402 #[inline(always)]
403 unsafe fn clone_waker<W: LocalWake + 'static>(waker: *const ()) -> RawWaker {
404 unsafe { Rc::increment_strong_count(waker as *const W) };
405 RawWaker::new(
406 waker,
407 &RawWakerVTable::new(clone_waker::<W>, wake::<W>, wake_by_ref::<W>, drop_waker::<W>),
408 )
409 }
410
411 // Wake by value, moving the Rc into the LocalWake::wake function
412 unsafe fn wake<W: LocalWake + 'static>(waker: *const ()) {
413 let waker = unsafe { Rc::from_raw(waker as *const W) };
414 <W as LocalWake>::wake(waker);
415 }
416
417 // Wake by reference, wrap the waker in ManuallyDrop to avoid dropping it
418 unsafe fn wake_by_ref<W: LocalWake + 'static>(waker: *const ()) {
419 let waker = unsafe { ManuallyDrop::new(Rc::from_raw(waker as *const W)) };
420 <W as LocalWake>::wake_by_ref(&waker);
421 }
422
423 // Decrement the reference count of the Rc on drop
424 unsafe fn drop_waker<W: LocalWake + 'static>(waker: *const ()) {
425 unsafe { Rc::decrement_strong_count(waker as *const W) };
426 }
427
428 RawWaker::new(
429 Rc::into_raw(waker) as *const (),
430 &RawWakerVTable::new(clone_waker::<W>, wake::<W>, wake_by_ref::<W>, drop_waker::<W>),
431 )
432}