Skip to main content

futures_util/stream/futures_unordered/
task.rs

1use super::{atomic, Arc, Weak};
2
3use core::cell::UnsafeCell;
4
5use atomic::Ordering::{self, Relaxed, SeqCst};
6use atomic::{AtomicBool, AtomicPtr};
7
8use super::abort::abort;
9use super::ReadyToRunQueue;
10
11/// Local version of `crate::arc_wake::ArcWake` to allow portable-atomic-util's
12/// `Arc` to be used.
13///
14/// A way of waking up a specific task.
15///
16/// By implementing this trait, types that are expected to be wrapped in an `Arc`
17/// can be converted into [`Waker`] objects.
18/// Those Wakers can be used to signal executors that a task it owns
19/// is ready to be `poll`ed again.
20///
21/// Currently, there are two ways to convert `ArcWake` into [`Waker`]:
22///
23/// * [`waker`](crate::task::waker()) converts `Arc<impl ArcWake>` into [`Waker`].
24/// * [`waker_ref`](crate::task::waker_ref()) converts `&Arc<impl ArcWake>` into [`WakerRef`] that
25///   provides access to a [`&Waker`][`Waker`].
26///
27/// [`Waker`]: std::task::Waker
28/// [`WakerRef`]: crate::task::WakerRef
29// Note: Send + Sync required because `Arc<T>` doesn't automatically imply
30// those bounds, but `Waker` implements them.
31pub(crate) trait ArcWake: Send + Sync {
32    /// Indicates that the associated task is ready to make progress and should
33    /// be `poll`ed.
34    ///
35    /// This function can be called from an arbitrary thread, including threads which
36    /// did not create the `ArcWake` based [`Waker`].
37    ///
38    /// Executors generally maintain a queue of "ready" tasks; `wake` should place
39    /// the associated task onto this queue.
40    ///
41    /// [`Waker`]: std::task::Waker
42    fn wake(this: Arc<Self>) {
43        Self::wake_by_ref(&this)
44    }
45
46    /// Indicates that the associated task is ready to make progress and should
47    /// be `poll`ed.
48    ///
49    /// This function can be called from an arbitrary thread, including threads which
50    /// did not create the `ArcWake` based [`Waker`].
51    ///
52    /// Executors generally maintain a queue of "ready" tasks; `wake_by_ref` should place
53    /// the associated task onto this queue.
54    ///
55    /// This function is similar to [`wake`](ArcWake::wake), but must not consume the provided data
56    /// pointer.
57    ///
58    /// [`Waker`]: std::task::Waker
59    fn wake_by_ref(arc_self: &Arc<Self>);
60}
61
62pub(super) struct Task<Fut> {
63    // The future
64    pub(super) future: UnsafeCell<Option<Fut>>,
65
66    // Next pointer for linked list tracking all active tasks (use
67    // `spin_next_all` to read when access is shared across threads)
68    pub(super) next_all: AtomicPtr<Task<Fut>>,
69
70    // Previous task in linked list tracking all active tasks
71    pub(super) prev_all: UnsafeCell<*const Task<Fut>>,
72
73    // Length of the linked list tracking all active tasks when this node was
74    // inserted (use `spin_next_all` to synchronize before reading when access
75    // is shared across threads)
76    pub(super) len_all: UnsafeCell<usize>,
77
78    // Next pointer in ready to run queue
79    pub(super) next_ready_to_run: AtomicPtr<Task<Fut>>,
80
81    // Queue that we'll be enqueued to when woken
82    pub(super) ready_to_run_queue: Weak<ReadyToRunQueue<Fut>>,
83
84    // Whether or not this task is currently in the ready to run queue
85    pub(super) queued: AtomicBool,
86
87    // Whether the future was awoken during polling
88    // It is possible for this flag to be set to true after the polling,
89    // but it will be ignored.
90    pub(super) woken: AtomicBool,
91}
92
93// `Task` can be sent across threads safely because it ensures that
94// the underlying `Fut` type isn't touched from any of its methods.
95//
96// The parent (`super`) module is trusted not to access `future`
97// across different threads.
98unsafe impl<Fut> Send for Task<Fut> {}
99unsafe impl<Fut> Sync for Task<Fut> {}
100
101impl<Fut> ArcWake for Task<Fut> {
102    fn wake_by_ref(arc_self: &Arc<Self>) {
103        let inner = match arc_self.ready_to_run_queue.upgrade() {
104            Some(inner) => inner,
105            None => return,
106        };
107
108        arc_self.woken.store(true, Relaxed);
109
110        // It's our job to enqueue this task it into the ready to run queue. To
111        // do this we set the `queued` flag, and if successful we then do the
112        // actual queueing operation, ensuring that we're only queued once.
113        //
114        // Once the task is inserted call `wake` to notify the parent task,
115        // as it'll want to come along and run our task later.
116        //
117        // Note that we don't change the reference count of the task here,
118        // we merely enqueue the raw pointer. The `FuturesUnordered`
119        // implementation guarantees that if we set the `queued` flag that
120        // there's a reference count held by the main `FuturesUnordered` queue
121        // still.
122        let prev = arc_self.queued.swap(true, SeqCst);
123        if !prev {
124            inner.enqueue(Arc::as_ptr(arc_self));
125            inner.waker.wake();
126        }
127    }
128}
129
130impl<Fut> Task<Fut> {
131    /// Returns a waker reference for this task without cloning the Arc.
132    pub(super) unsafe fn waker_ref(this: &Arc<Self>) -> waker_ref::WakerRef<'_> {
133        unsafe { waker_ref::waker_ref(this) }
134    }
135
136    /// Spins until `next_all` is no longer set to `pending_next_all`.
137    ///
138    /// The temporary `pending_next_all` value is typically overwritten fairly
139    /// quickly after a node is inserted into the list of all futures, so this
140    /// should rarely spin much.
141    ///
142    /// When it returns, the correct `next_all` value is returned.
143    ///
144    /// `Relaxed` or `Acquire` ordering can be used. `Acquire` ordering must be
145    /// used before `len_all` can be safely read.
146    #[inline]
147    pub(super) fn spin_next_all(
148        &self,
149        pending_next_all: *mut Self,
150        ordering: Ordering,
151    ) -> *const Self {
152        loop {
153            let next = self.next_all.load(ordering);
154            if next != pending_next_all {
155                return next;
156            }
157        }
158    }
159}
160
161impl<Fut> Drop for Task<Fut> {
162    fn drop(&mut self) {
163        // Since `Task<Fut>` is sent across all threads for any lifetime,
164        // regardless of `Fut`, we, to guarantee memory safety, can't actually
165        // touch `Fut` at any time except when we have a reference to the
166        // `FuturesUnordered` itself .
167        //
168        // Consequently it *should* be the case that we always drop futures from
169        // the `FuturesUnordered` instance. This is a bomb, just in case there's
170        // a bug in that logic.
171        unsafe {
172            if (*self.future.get()).is_some() {
173                abort("future still here when dropping");
174            }
175        }
176    }
177}
178
179mod waker_ref {
180    use super::ArcWake;
181    #[cfg(not(feature = "portable-atomic-alloc"))]
182    use alloc::sync::Arc;
183    use core::marker::PhantomData;
184    use core::mem;
185    use core::mem::ManuallyDrop;
186    use core::ops::Deref;
187    use core::task::{RawWaker, RawWakerVTable, Waker};
188    #[cfg(feature = "portable-atomic-alloc")]
189    use portable_atomic_util::Arc;
190
191    pub(crate) struct WakerRef<'a> {
192        waker: ManuallyDrop<Waker>,
193        _marker: PhantomData<&'a ()>,
194    }
195
196    impl WakerRef<'_> {
197        #[inline]
198        fn new_unowned(waker: ManuallyDrop<Waker>) -> Self {
199            Self { waker, _marker: PhantomData }
200        }
201    }
202
203    impl Deref for WakerRef<'_> {
204        type Target = Waker;
205
206        #[inline]
207        fn deref(&self) -> &Waker {
208            &self.waker
209        }
210    }
211
212    /// Copy of `future_task::waker_ref` without `W: 'static` bound.
213    ///
214    /// # Safety
215    ///
216    /// The caller must guarantee that use-after-free will not occur.
217    #[inline]
218    pub(crate) unsafe fn waker_ref<W>(wake: &Arc<W>) -> WakerRef<'_>
219    where
220        W: ArcWake,
221    {
222        // simply copy the pointer instead of using Arc::into_raw,
223        // as we don't actually keep a refcount by using ManuallyDrop.<
224        let ptr = Arc::as_ptr(wake).cast::<()>();
225
226        let waker =
227            ManuallyDrop::new(unsafe { Waker::from_raw(RawWaker::new(ptr, waker_vtable::<W>())) });
228        WakerRef::new_unowned(waker)
229    }
230
231    fn waker_vtable<W: ArcWake>() -> &'static RawWakerVTable {
232        &RawWakerVTable::new(
233            clone_arc_raw::<W>,
234            wake_arc_raw::<W>,
235            wake_by_ref_arc_raw::<W>,
236            drop_arc_raw::<W>,
237        )
238    }
239
240    // FIXME: panics on Arc::clone / refcount changes could wreak havoc on the
241    // code here. We should guard against this by aborting.
242
243    unsafe fn increase_refcount<T: ArcWake>(data: *const ()) {
244        // Retain Arc, but don't touch refcount by wrapping in ManuallyDrop
245        let arc = mem::ManuallyDrop::new(unsafe { Arc::<T>::from_raw(data.cast::<T>()) });
246        // Now increase refcount, but don't drop new refcount either
247        let _arc_clone: mem::ManuallyDrop<_> = arc.clone();
248    }
249
250    unsafe fn clone_arc_raw<T: ArcWake>(data: *const ()) -> RawWaker {
251        unsafe { increase_refcount::<T>(data) }
252        RawWaker::new(data, waker_vtable::<T>())
253    }
254
255    unsafe fn wake_arc_raw<T: ArcWake>(data: *const ()) {
256        let arc: Arc<T> = unsafe { Arc::from_raw(data.cast::<T>()) };
257        ArcWake::wake(arc);
258    }
259
260    unsafe fn wake_by_ref_arc_raw<T: ArcWake>(data: *const ()) {
261        // Retain Arc, but don't touch refcount by wrapping in ManuallyDrop
262        let arc = mem::ManuallyDrop::new(unsafe { Arc::<T>::from_raw(data.cast::<T>()) });
263        ArcWake::wake_by_ref(&arc);
264    }
265
266    unsafe fn drop_arc_raw<T: ArcWake>(data: *const ()) {
267        drop(unsafe { Arc::<T>::from_raw(data.cast::<T>()) })
268    }
269}