portable_atomic_util/task.rs
1// SPDX-License-Identifier: Apache-2.0 OR MIT
2
3//! Types and Traits for working with asynchronous tasks.
4
5// This module is based on alloc::task::Wake.
6//
7// The code has been adjusted to work with stable Rust.
8//
9// Source: https://github.com/rust-lang/rust/blob/1.84.0/library/alloc/src/task.rs.
10//
11// Copyright & License of the original code:
12// - https://github.com/rust-lang/rust/blob/1.84.0/COPYRIGHT
13// - https://github.com/rust-lang/rust/blob/1.84.0/LICENSE-APACHE
14// - https://github.com/rust-lang/rust/blob/1.84.0/LICENSE-MIT
15
16use core::{
17 mem::ManuallyDrop,
18 task::{RawWaker, RawWakerVTable, Waker},
19};
20
21use crate::Arc;
22
23/// The implementation of waking a task on an executor.
24///
25/// This is an equivalent to [`std::task::Wake`], but using [`portable_atomic_util::Arc`](crate::Arc)
26/// as a reference-counted pointer. See the documentation for [`std::task::Wake`] for more details.
27///
28/// **Note:** Unlike `std::task::Wake`, all methods take `this:` instead of `self:`.
29/// This is because using `portable_atomic_util::Arc` as a receiver requires the
30/// [unstable `arbitrary_self_types` feature](https://github.com/rust-lang/rust/issues/44874).
31///
32/// # Examples
33///
34/// A basic `block_on` function that takes a future and runs it to completion on
35/// the current thread.
36///
37/// **Note:** This example trades correctness for simplicity. In order to prevent
38/// deadlocks, production-grade implementations will also need to handle
39/// intermediate calls to `thread::unpark` as well as nested invocations.
40///
41/// ```
42/// use std::{
43/// future::Future,
44/// task::{Context, Poll},
45/// thread::{self, Thread},
46/// };
47///
48/// use portable_atomic_util::{Arc, task::Wake};
49///
50/// /// A waker that wakes up the current thread when called.
51/// struct ThreadWaker(Thread);
52///
53/// impl Wake for ThreadWaker {
54/// fn wake(this: Arc<Self>) {
55/// this.0.unpark();
56/// }
57/// }
58///
59/// /// Run a future to completion on the current thread.
60/// fn block_on<T>(fut: impl Future<Output = T>) -> T {
61/// // Pin the future so it can be polled.
62/// let mut fut = Box::pin(fut);
63///
64/// // Create a new context to be passed to the future.
65/// let t = thread::current();
66/// let waker = Arc::new(ThreadWaker(t)).into();
67/// let mut cx = Context::from_waker(&waker);
68///
69/// // Run the future to completion.
70/// loop {
71/// match fut.as_mut().poll(&mut cx) {
72/// Poll::Ready(res) => return res,
73/// Poll::Pending => thread::park(),
74/// }
75/// }
76/// }
77///
78/// block_on(async {
79/// println!("Hi from inside a future!");
80/// });
81/// ```
82pub trait Wake {
83 /// Wake this task.
84 fn wake(this: Arc<Self>);
85
86 /// Wake this task without consuming the waker.
87 ///
88 /// If an executor supports a cheaper way to wake without consuming the
89 /// waker, it should override this method. By default, it clones the
90 /// [`Arc`] and calls [`wake`] on the clone.
91 ///
92 /// [`wake`]: Wake::wake
93 fn wake_by_ref(this: &Arc<Self>) {
94 Self::wake(this.clone());
95 }
96}
97impl<W: Wake + Send + Sync + 'static> From<Arc<W>> for Waker {
98 /// Use a [`Wake`]-able type as a `Waker`.
99 ///
100 /// No heap allocations or atomic operations are used for this conversion.
101 fn from(waker: Arc<W>) -> Self {
102 // SAFETY: This is safe because raw_waker safely constructs
103 // a RawWaker from Arc<W>.
104 unsafe { Self::from_raw(raw_waker(waker)) }
105 }
106}
107impl<W: Wake + Send + Sync + 'static> From<Arc<W>> for RawWaker {
108 /// Use a `Wake`-able type as a `RawWaker`.
109 ///
110 /// No heap allocations or atomic operations are used for this conversion.
111 fn from(waker: Arc<W>) -> Self {
112 raw_waker(waker)
113 }
114}
115
116// NB: This private function for constructing a RawWaker is used, rather than
117// inlining this into the `From<Arc<W>> for RawWaker` impl, to ensure that
118// the safety of `From<Arc<W>> for Waker` does not depend on the correct
119// trait dispatch - instead both impls call this function directly and
120// explicitly.
121#[inline(always)]
122fn raw_waker<W: Wake + Send + Sync + 'static>(waker: Arc<W>) -> RawWaker {
123 // Increment the reference count of the arc to clone it.
124 //
125 // The #[inline(always)] is to ensure that raw_waker and clone_waker are
126 // always generated in the same code generation unit as one another, and
127 // therefore that the structurally identical const-promoted RawWakerVTable
128 // within both functions is deduplicated at LLVM IR code generation time.
129 // This allows optimizing Waker::will_wake to a single pointer comparison of
130 // the vtable pointers, rather than comparing all four function pointers
131 // within the vtables.
132 #[inline(always)]
133 unsafe fn clone_waker<W: Wake + Send + Sync + 'static>(waker: *const ()) -> RawWaker {
134 // SAFETY: the caller must uphold the safety contract.
135 unsafe { Arc::increment_strong_count(waker as *const W) }
136 RawWaker::new(
137 waker,
138 &RawWakerVTable::new(clone_waker::<W>, wake::<W>, wake_by_ref::<W>, drop_waker::<W>),
139 )
140 }
141
142 // Wake by value, moving the Arc into the Wake::wake function
143 unsafe fn wake<W: Wake + Send + Sync + 'static>(waker: *const ()) {
144 // SAFETY: the caller must uphold the safety contract.
145 let waker = unsafe { Arc::from_raw(waker as *const W) };
146 <W as Wake>::wake(waker);
147 }
148
149 // Wake by reference, wrap the waker in ManuallyDrop to avoid dropping it
150 unsafe fn wake_by_ref<W: Wake + Send + Sync + 'static>(waker: *const ()) {
151 // SAFETY: the caller must uphold the safety contract.
152 let waker = unsafe { ManuallyDrop::new(Arc::from_raw(waker as *const W)) };
153 <W as Wake>::wake_by_ref(&waker);
154 }
155
156 // Decrement the reference count of the Arc on drop
157 unsafe fn drop_waker<W: Wake + Send + Sync + 'static>(waker: *const ()) {
158 // SAFETY: the caller must uphold the safety contract.
159 unsafe { Arc::decrement_strong_count(waker as *const W) }
160 }
161
162 RawWaker::new(
163 Arc::into_raw(waker) as *const (),
164 &RawWakerVTable::new(clone_waker::<W>, wake::<W>, wake_by_ref::<W>, drop_waker::<W>),
165 )
166}