Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs
This commit is contained in:
+157
@@ -0,0 +1,157 @@
|
||||
//! An [`AbortOnDropHandle`] is like a [`JoinHandle`], except that it
|
||||
//! will abort the task as soon as it is dropped.
|
||||
//!
|
||||
//! Correspondingly, an [`AbortOnDrop`] is like a [`AbortHandle`] that will abort
|
||||
//! the task as soon as it is dropped.
|
||||
|
||||
use tokio::task::{AbortHandle, JoinError, JoinHandle};
|
||||
|
||||
use std::{
|
||||
future::Future,
|
||||
mem::ManuallyDrop,
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
/// A wrapper around a [`tokio::task::JoinHandle`],
|
||||
/// which [aborts] the task when it is dropped.
|
||||
///
|
||||
/// [aborts]: tokio::task::JoinHandle::abort
|
||||
#[must_use = "Dropping the handle aborts the task immediately"]
|
||||
pub struct AbortOnDropHandle<T>(JoinHandle<T>);
|
||||
|
||||
impl<T> Drop for AbortOnDropHandle<T> {
|
||||
fn drop(&mut self) {
|
||||
self.abort()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> AbortOnDropHandle<T> {
|
||||
/// Create an [`AbortOnDropHandle`] from a [`JoinHandle`].
|
||||
pub fn new(handle: JoinHandle<T>) -> Self {
|
||||
Self(handle)
|
||||
}
|
||||
|
||||
/// Abort the task associated with this handle,
|
||||
/// equivalent to [`JoinHandle::abort`].
|
||||
#[inline]
|
||||
pub fn abort(&self) {
|
||||
self.0.abort()
|
||||
}
|
||||
|
||||
/// Checks if the task associated with this handle is finished,
|
||||
/// equivalent to [`JoinHandle::is_finished`].
|
||||
#[inline]
|
||||
pub fn is_finished(&self) -> bool {
|
||||
self.0.is_finished()
|
||||
}
|
||||
|
||||
/// Returns a new [`AbortHandle`] that can be used to remotely abort this task,
|
||||
/// equivalent to [`JoinHandle::abort_handle`].
|
||||
pub fn abort_handle(&self) -> AbortHandle {
|
||||
self.0.abort_handle()
|
||||
}
|
||||
|
||||
/// Cancels aborting on drop and returns the original [`JoinHandle`].
|
||||
pub fn detach(self) -> JoinHandle<T> {
|
||||
// Avoid invoking `AbortOnDropHandle`'s `Drop` impl
|
||||
let this = ManuallyDrop::new(self);
|
||||
// SAFETY: `&this.0` is a reference, so it is certainly initialized, and
|
||||
// it won't be double-dropped because it's in a `ManuallyDrop`
|
||||
unsafe { std::ptr::read(&this.0) }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> std::fmt::Debug for AbortOnDropHandle<T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("AbortOnDropHandle")
|
||||
.field("id", &self.0.id())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Future for AbortOnDropHandle<T> {
|
||||
type Output = Result<T, JoinError>;
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
Pin::new(&mut self.0).poll(cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> AsRef<JoinHandle<T>> for AbortOnDropHandle<T> {
|
||||
fn as_ref(&self) -> &JoinHandle<T> {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// A wrapper around a [`tokio::task::AbortHandle`],
|
||||
/// which [aborts] the task when it is dropped.
|
||||
///
|
||||
/// Unlike [`AbortOnDropHandle`], [`AbortOnDrop`] cannot be `.await`ed for a result.
|
||||
///
|
||||
/// It has no generic parameter, making it suitable when you only need to keep
|
||||
/// a task handle in a struct and do not care about the output.
|
||||
///
|
||||
/// [aborts]: tokio::task::AbortHandle::abort
|
||||
#[must_use = "Dropping the handle aborts the task immediately"]
|
||||
pub struct AbortOnDrop(AbortHandle);
|
||||
|
||||
impl Drop for AbortOnDrop {
|
||||
fn drop(&mut self) {
|
||||
self.abort()
|
||||
}
|
||||
}
|
||||
|
||||
impl AbortOnDrop {
|
||||
/// Create an [`AbortOnDrop`] from a [`AbortHandle`].
|
||||
pub fn new(handle: AbortHandle) -> Self {
|
||||
Self(handle)
|
||||
}
|
||||
|
||||
/// Abort the task associated with this handle,
|
||||
/// equivalent to [`AbortHandle::abort`].
|
||||
#[inline]
|
||||
pub fn abort(&self) {
|
||||
self.0.abort()
|
||||
}
|
||||
|
||||
/// Checks if the task associated with this handle is finished,
|
||||
/// equivalent to [`AbortHandle::is_finished`].
|
||||
#[inline]
|
||||
pub fn is_finished(&self) -> bool {
|
||||
self.0.is_finished()
|
||||
}
|
||||
|
||||
/// Cancels aborting on drop and returns the original [`AbortHandle`].
|
||||
pub fn detach(self) -> AbortHandle {
|
||||
// Avoid invoking `AbortOnDrop`'s `Drop` impl
|
||||
let this = ManuallyDrop::new(self);
|
||||
// SAFETY: `&this.0` is a reference, so it is certainly initialized, and
|
||||
// it won't be double-dropped because it's in a `ManuallyDrop`
|
||||
unsafe { std::ptr::read(&this.0) }
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for AbortOnDrop {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("AbortOnDrop")
|
||||
.field("id", &self.0.id())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A simple type that does not implement [`std::fmt::Debug`].
|
||||
struct NotDebug;
|
||||
|
||||
fn is_debug<T: std::fmt::Debug>() {}
|
||||
|
||||
#[test]
|
||||
fn assert_debug() {
|
||||
is_debug::<AbortOnDrop>();
|
||||
is_debug::<AbortOnDropHandle<NotDebug>>();
|
||||
}
|
||||
}
|
||||
+904
@@ -0,0 +1,904 @@
|
||||
use hashbrown::hash_table::Entry;
|
||||
use hashbrown::{HashMap, HashTable};
|
||||
use std::borrow::Borrow;
|
||||
use std::collections::hash_map::RandomState;
|
||||
use std::fmt;
|
||||
use std::future::Future;
|
||||
use std::hash::{BuildHasher, Hash};
|
||||
use std::marker::PhantomData;
|
||||
use tokio::runtime::Handle;
|
||||
use tokio::task::{AbortHandle, Id, JoinError, JoinSet, LocalSet};
|
||||
|
||||
/// A collection of tasks spawned on a Tokio runtime, associated with hash map
|
||||
/// keys.
|
||||
///
|
||||
/// This type is very similar to the [`JoinSet`] type in `tokio::task`, with the
|
||||
/// addition of a set of keys associated with each task. These keys allow
|
||||
/// [cancelling a task][abort] or [multiple tasks][abort_matching] in the
|
||||
/// `JoinMap` based on their keys, or [test whether a task corresponding to a
|
||||
/// given key exists][contains] in the `JoinMap`.
|
||||
///
|
||||
/// In addition, when tasks in the `JoinMap` complete, they will return the
|
||||
/// associated key along with the value returned by the task, if any.
|
||||
///
|
||||
/// A `JoinMap` can be used to await the completion of some or all of the tasks
|
||||
/// in the map. The map is not ordered, and the tasks will be returned in the
|
||||
/// order they complete.
|
||||
///
|
||||
/// All of the tasks must have the same return type `V`.
|
||||
///
|
||||
/// When the `JoinMap` is dropped, all tasks in the `JoinMap` are immediately aborted.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Spawn multiple tasks and wait for them:
|
||||
///
|
||||
/// ```
|
||||
/// use tokio_util::task::JoinMap;
|
||||
///
|
||||
/// # #[tokio::main(flavor = "current_thread")]
|
||||
/// # async fn main() {
|
||||
/// let mut map = JoinMap::new();
|
||||
///
|
||||
/// for i in 0..10 {
|
||||
/// // Spawn a task on the `JoinMap` with `i` as its key.
|
||||
/// map.spawn(i, async move { /* ... */ });
|
||||
/// }
|
||||
///
|
||||
/// let mut seen = [false; 10];
|
||||
///
|
||||
/// // When a task completes, `join_next` returns the task's key along
|
||||
/// // with its output.
|
||||
/// while let Some((key, res)) = map.join_next().await {
|
||||
/// seen[key] = true;
|
||||
/// assert!(res.is_ok(), "task {} completed successfully!", key);
|
||||
/// }
|
||||
///
|
||||
/// for i in 0..10 {
|
||||
/// assert!(seen[i]);
|
||||
/// }
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// Cancel tasks based on their keys:
|
||||
///
|
||||
/// ```
|
||||
/// use tokio_util::task::JoinMap;
|
||||
///
|
||||
/// # #[tokio::main(flavor = "current_thread")]
|
||||
/// # async fn main() {
|
||||
/// let mut map = JoinMap::new();
|
||||
///
|
||||
/// map.spawn("hello world", std::future::ready(1));
|
||||
/// map.spawn("goodbye world", std::future::pending());
|
||||
///
|
||||
/// // Look up the "goodbye world" task in the map and abort it.
|
||||
/// let aborted = map.abort("goodbye world");
|
||||
///
|
||||
/// // `JoinMap::abort` returns `true` if a task existed for the
|
||||
/// // provided key.
|
||||
/// assert!(aborted);
|
||||
///
|
||||
/// while let Some((key, res)) = map.join_next().await {
|
||||
/// if key == "goodbye world" {
|
||||
/// // The aborted task should complete with a cancelled `JoinError`.
|
||||
/// assert!(res.unwrap_err().is_cancelled());
|
||||
/// } else {
|
||||
/// // Other tasks should complete normally.
|
||||
/// assert_eq!(res.unwrap(), 1);
|
||||
/// }
|
||||
/// }
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// [`JoinSet`]: tokio::task::JoinSet
|
||||
/// [abort]: fn@Self::abort
|
||||
/// [abort_matching]: fn@Self::abort_matching
|
||||
/// [contains]: fn@Self::contains_key
|
||||
pub struct JoinMap<K, V, S = RandomState> {
|
||||
/// A map of the [`AbortHandle`]s of the tasks spawned on this `JoinMap`,
|
||||
/// indexed by their keys.
|
||||
tasks_by_key: HashTable<(K, AbortHandle)>,
|
||||
|
||||
/// A map from task IDs to the hash of the key associated with that task.
|
||||
///
|
||||
/// This map is used to perform reverse lookups of tasks in the
|
||||
/// `tasks_by_key` map based on their task IDs. When a task terminates, the
|
||||
/// ID is provided to us by the `JoinSet`, so we can look up the hash value
|
||||
/// of that task's key, and then remove it from the `tasks_by_key` map using
|
||||
/// the raw hash code, resolving collisions by comparing task IDs.
|
||||
hashes_by_task: HashMap<Id, u64, S>,
|
||||
|
||||
/// The [`JoinSet`] that awaits the completion of tasks spawned on this
|
||||
/// `JoinMap`.
|
||||
tasks: JoinSet<V>,
|
||||
}
|
||||
|
||||
impl<K, V> JoinMap<K, V> {
|
||||
/// Creates a new empty `JoinMap`.
|
||||
///
|
||||
/// The `JoinMap` is initially created with a capacity of 0, so it will not
|
||||
/// allocate until a task is first spawned on it.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use tokio_util::task::JoinMap;
|
||||
/// let map: JoinMap<&str, i32> = JoinMap::new();
|
||||
/// ```
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self::with_hasher(RandomState::new())
|
||||
}
|
||||
|
||||
/// Creates an empty `JoinMap` with the specified capacity.
|
||||
///
|
||||
/// The `JoinMap` will be able to hold at least `capacity` tasks without
|
||||
/// reallocating.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use tokio_util::task::JoinMap;
|
||||
/// let map: JoinMap<&str, i32> = JoinMap::with_capacity(10);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn with_capacity(capacity: usize) -> Self {
|
||||
JoinMap::with_capacity_and_hasher(capacity, Default::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl<K, V, S> JoinMap<K, V, S> {
|
||||
/// Creates an empty `JoinMap` which will use the given hash builder to hash
|
||||
/// keys.
|
||||
///
|
||||
/// The created map has the default initial capacity.
|
||||
///
|
||||
/// Warning: `hash_builder` is normally randomly generated, and
|
||||
/// is designed to allow `JoinMap` to be resistant to attacks that
|
||||
/// cause many collisions and very poor performance. Setting it
|
||||
/// manually using this function can expose a DoS attack vector.
|
||||
///
|
||||
/// The `hash_builder` passed should implement the [`BuildHasher`] trait for
|
||||
/// the `JoinMap` to be useful, see its documentation for details.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn with_hasher(hash_builder: S) -> Self {
|
||||
Self::with_capacity_and_hasher(0, hash_builder)
|
||||
}
|
||||
|
||||
/// Creates an empty `JoinMap` with the specified capacity, using `hash_builder`
|
||||
/// to hash the keys.
|
||||
///
|
||||
/// The `JoinMap` will be able to hold at least `capacity` elements without
|
||||
/// reallocating. If `capacity` is 0, the `JoinMap` will not allocate.
|
||||
///
|
||||
/// Warning: `hash_builder` is normally randomly generated, and
|
||||
/// is designed to allow HashMaps to be resistant to attacks that
|
||||
/// cause many collisions and very poor performance. Setting it
|
||||
/// manually using this function can expose a DoS attack vector.
|
||||
///
|
||||
/// The `hash_builder` passed should implement the [`BuildHasher`] trait for
|
||||
/// the `JoinMap`to be useful, see its documentation for details.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// # #[tokio::main(flavor = "current_thread")]
|
||||
/// # async fn main() {
|
||||
/// use tokio_util::task::JoinMap;
|
||||
/// use std::collections::hash_map::RandomState;
|
||||
///
|
||||
/// let s = RandomState::new();
|
||||
/// let mut map = JoinMap::with_capacity_and_hasher(10, s);
|
||||
/// map.spawn(1, async move { "hello world!" });
|
||||
/// # }
|
||||
/// ```
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self {
|
||||
Self {
|
||||
tasks_by_key: HashTable::with_capacity(capacity),
|
||||
hashes_by_task: HashMap::with_capacity_and_hasher(capacity, hash_builder),
|
||||
tasks: JoinSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the number of tasks currently in the `JoinMap`.
|
||||
pub fn len(&self) -> usize {
|
||||
let len = self.tasks_by_key.len();
|
||||
debug_assert_eq!(len, self.hashes_by_task.len());
|
||||
len
|
||||
}
|
||||
|
||||
/// Returns whether the `JoinMap` is empty.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
let empty = self.tasks_by_key.is_empty();
|
||||
debug_assert_eq!(empty, self.hashes_by_task.is_empty());
|
||||
empty
|
||||
}
|
||||
|
||||
/// Returns the number of tasks the map can hold without reallocating.
|
||||
///
|
||||
/// This number is a lower bound; the `JoinMap` might be able to hold
|
||||
/// more, but is guaranteed to be able to hold at least this many.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use tokio_util::task::JoinMap;
|
||||
///
|
||||
/// let map: JoinMap<i32, i32> = JoinMap::with_capacity(100);
|
||||
/// assert!(map.capacity() >= 100);
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn capacity(&self) -> usize {
|
||||
let capacity = self.tasks_by_key.capacity();
|
||||
debug_assert_eq!(capacity, self.hashes_by_task.capacity());
|
||||
capacity
|
||||
}
|
||||
}
|
||||
|
||||
impl<K, V, S> JoinMap<K, V, S>
|
||||
where
|
||||
K: Hash + Eq,
|
||||
V: 'static,
|
||||
S: BuildHasher,
|
||||
{
|
||||
/// Spawn the provided task and store it in this `JoinMap` with the provided
|
||||
/// key.
|
||||
///
|
||||
/// If a task previously existed in the `JoinMap` for this key, that task
|
||||
/// will be cancelled and replaced with the new one. The previous task will
|
||||
/// be removed from the `JoinMap`; a subsequent call to [`join_next`] will
|
||||
/// *not* return a cancelled [`JoinError`] for that task.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This method panics if called outside of a Tokio runtime.
|
||||
///
|
||||
/// [`join_next`]: Self::join_next
|
||||
#[track_caller]
|
||||
pub fn spawn<F>(&mut self, key: K, task: F)
|
||||
where
|
||||
F: Future<Output = V>,
|
||||
F: Send + 'static,
|
||||
V: Send,
|
||||
{
|
||||
let task = self.tasks.spawn(task);
|
||||
self.insert(key, task)
|
||||
}
|
||||
|
||||
/// Spawn the provided task on the provided runtime and store it in this
|
||||
/// `JoinMap` with the provided key.
|
||||
///
|
||||
/// If a task previously existed in the `JoinMap` for this key, that task
|
||||
/// will be cancelled and replaced with the new one. The previous task will
|
||||
/// be removed from the `JoinMap`; a subsequent call to [`join_next`] will
|
||||
/// *not* return a cancelled [`JoinError`] for that task.
|
||||
///
|
||||
/// [`join_next`]: Self::join_next
|
||||
#[track_caller]
|
||||
pub fn spawn_on<F>(&mut self, key: K, task: F, handle: &Handle)
|
||||
where
|
||||
F: Future<Output = V>,
|
||||
F: Send + 'static,
|
||||
V: Send,
|
||||
{
|
||||
let task = self.tasks.spawn_on(task, handle);
|
||||
self.insert(key, task);
|
||||
}
|
||||
|
||||
/// Spawn the blocking code on the blocking threadpool and store it in this `JoinMap` with the provided
|
||||
/// key.
|
||||
///
|
||||
/// If a task previously existed in the `JoinMap` for this key, that task
|
||||
/// will be cancelled and replaced with the new one. The previous task will
|
||||
/// be removed from the `JoinMap`; a subsequent call to [`join_next`] will
|
||||
/// *not* return a cancelled [`JoinError`] for that task.
|
||||
///
|
||||
/// Note that blocking tasks cannot be cancelled after execution starts.
|
||||
/// Replaced blocking tasks will still run to completion if the task has begun
|
||||
/// to execute when it is replaced. A blocking task which is replaced before
|
||||
/// it has been scheduled on a blocking worker thread will be cancelled.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This method panics if called outside of a Tokio runtime.
|
||||
///
|
||||
/// [`join_next`]: Self::join_next
|
||||
#[track_caller]
|
||||
pub fn spawn_blocking<F>(&mut self, key: K, f: F)
|
||||
where
|
||||
F: FnOnce() -> V,
|
||||
F: Send + 'static,
|
||||
V: Send,
|
||||
{
|
||||
let task = self.tasks.spawn_blocking(f);
|
||||
self.insert(key, task)
|
||||
}
|
||||
|
||||
/// Spawn the blocking code on the blocking threadpool of the provided runtime and store it in this
|
||||
/// `JoinMap` with the provided key.
|
||||
///
|
||||
/// If a task previously existed in the `JoinMap` for this key, that task
|
||||
/// will be cancelled and replaced with the new one. The previous task will
|
||||
/// be removed from the `JoinMap`; a subsequent call to [`join_next`] will
|
||||
/// *not* return a cancelled [`JoinError`] for that task.
|
||||
///
|
||||
/// Note that blocking tasks cannot be cancelled after execution starts.
|
||||
/// Replaced blocking tasks will still run to completion if the task has begun
|
||||
/// to execute when it is replaced. A blocking task which is replaced before
|
||||
/// it has been scheduled on a blocking worker thread will be cancelled.
|
||||
///
|
||||
/// [`join_next`]: Self::join_next
|
||||
#[track_caller]
|
||||
pub fn spawn_blocking_on<F>(&mut self, key: K, f: F, handle: &Handle)
|
||||
where
|
||||
F: FnOnce() -> V,
|
||||
F: Send + 'static,
|
||||
V: Send,
|
||||
{
|
||||
let task = self.tasks.spawn_blocking_on(f, handle);
|
||||
self.insert(key, task);
|
||||
}
|
||||
|
||||
/// Spawn the provided task on the current [`LocalSet`] or [`LocalRuntime`]
|
||||
/// and store it in this `JoinMap` with the provided key.
|
||||
///
|
||||
/// If a task previously existed in the `JoinMap` for this key, that task
|
||||
/// will be cancelled and replaced with the new one. The previous task will
|
||||
/// be removed from the `JoinMap`; a subsequent call to [`join_next`] will
|
||||
/// *not* return a cancelled [`JoinError`] for that task.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This method panics if it is called outside of a `LocalSet` or `LocalRuntime`.
|
||||
///
|
||||
/// [`LocalSet`]: tokio::task::LocalSet
|
||||
/// [`LocalRuntime`]: tokio::runtime::LocalRuntime
|
||||
/// [`join_next`]: Self::join_next
|
||||
#[track_caller]
|
||||
pub fn spawn_local<F>(&mut self, key: K, task: F)
|
||||
where
|
||||
F: Future<Output = V>,
|
||||
F: 'static,
|
||||
{
|
||||
let task = self.tasks.spawn_local(task);
|
||||
self.insert(key, task);
|
||||
}
|
||||
|
||||
/// Spawn the provided task on the provided [`LocalSet`] and store it in
|
||||
/// this `JoinMap` with the provided key.
|
||||
///
|
||||
/// If a task previously existed in the `JoinMap` for this key, that task
|
||||
/// will be cancelled and replaced with the new one. The previous task will
|
||||
/// be removed from the `JoinMap`; a subsequent call to [`join_next`] will
|
||||
/// *not* return a cancelled [`JoinError`] for that task.
|
||||
///
|
||||
/// [`LocalSet`]: tokio::task::LocalSet
|
||||
/// [`join_next`]: Self::join_next
|
||||
#[track_caller]
|
||||
pub fn spawn_local_on<F>(&mut self, key: K, task: F, local_set: &LocalSet)
|
||||
where
|
||||
F: Future<Output = V>,
|
||||
F: 'static,
|
||||
{
|
||||
let task = self.tasks.spawn_local_on(task, local_set);
|
||||
self.insert(key, task)
|
||||
}
|
||||
|
||||
fn insert(&mut self, mut key: K, mut abort: AbortHandle) {
|
||||
let hash_builder = self.hashes_by_task.hasher();
|
||||
let hash = hash_builder.hash_one(&key);
|
||||
let id = abort.id();
|
||||
|
||||
// Insert the new key into the map of tasks by keys.
|
||||
let entry =
|
||||
self.tasks_by_key
|
||||
.entry(hash, |(k, _)| *k == key, |(k, _)| hash_builder.hash_one(k));
|
||||
match entry {
|
||||
Entry::Occupied(occ) => {
|
||||
// There was a previous task spawned with the same key! Cancel
|
||||
// that task, and remove its ID from the map of hashes by task IDs.
|
||||
(key, abort) = std::mem::replace(occ.into_mut(), (key, abort));
|
||||
|
||||
// Remove the old task ID.
|
||||
let _prev_hash = self.hashes_by_task.remove(&abort.id());
|
||||
debug_assert_eq!(Some(hash), _prev_hash);
|
||||
|
||||
// Associate the key's hash with the new task's ID, for looking up tasks by ID.
|
||||
let _prev = self.hashes_by_task.insert(id, hash);
|
||||
debug_assert!(_prev.is_none(), "no prior task should have had the same ID");
|
||||
|
||||
// Note: it's important to drop `key` and abort the task here.
|
||||
// This defends against any panics during drop handling for causing inconsistent state.
|
||||
abort.abort();
|
||||
drop(key);
|
||||
}
|
||||
Entry::Vacant(vac) => {
|
||||
vac.insert((key, abort));
|
||||
|
||||
// Associate the key's hash with this task's ID, for looking up tasks by ID.
|
||||
let _prev = self.hashes_by_task.insert(id, hash);
|
||||
debug_assert!(_prev.is_none(), "no prior task should have had the same ID");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Waits until one of the tasks in the map completes and returns its
|
||||
/// output, along with the key corresponding to that task.
|
||||
///
|
||||
/// Returns `None` if the map is empty.
|
||||
///
|
||||
/// # Cancel Safety
|
||||
///
|
||||
/// This method is cancel safe. If `join_next` is used as the event in a [`tokio::select!`]
|
||||
/// statement and some other branch completes first, it is guaranteed that no tasks were
|
||||
/// removed from this `JoinMap`.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// This function returns:
|
||||
///
|
||||
/// * `Some((key, Ok(value)))` if one of the tasks in this `JoinMap` has
|
||||
/// completed. The `value` is the return value of that ask, and `key` is
|
||||
/// the key associated with the task.
|
||||
/// * `Some((key, Err(err)))` if one of the tasks in this `JoinMap` has
|
||||
/// panicked or been aborted. `key` is the key associated with the task
|
||||
/// that panicked or was aborted.
|
||||
/// * `None` if the `JoinMap` is empty.
|
||||
///
|
||||
/// [`tokio::select!`]: https://docs.rs/tokio/latest/tokio/macro.select.html
|
||||
pub async fn join_next(&mut self) -> Option<(K, Result<V, JoinError>)> {
|
||||
loop {
|
||||
let (res, id) = match self.tasks.join_next_with_id().await {
|
||||
Some(Ok((id, output))) => (Ok(output), id),
|
||||
Some(Err(e)) => {
|
||||
let id = e.id();
|
||||
(Err(e), id)
|
||||
}
|
||||
None => return None,
|
||||
};
|
||||
if let Some(key) = self.remove_by_id(id) {
|
||||
break Some((key, res));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Tries to join one of the tasks in the map that has completed and
|
||||
/// returns its output, along with the key corresponding to that task.
|
||||
///
|
||||
/// Returns `None` if there are no completed tasks, or if the map is empty.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// This function returns:
|
||||
///
|
||||
/// * `Some((key, Ok(value)))` if one of the tasks in this `JoinMap` has
|
||||
/// completed. The `value` is the return value of that task, and `key`
|
||||
/// is the key associated with the task.
|
||||
/// * `Some((key, Err(err)))` if one of the tasks in this `JoinMap` has
|
||||
/// panicked or been aborted. `key` is the key associated with the task
|
||||
/// that panicked or was aborted.
|
||||
/// * `None` if there are no completed tasks ready to be joined, or the
|
||||
/// `JoinMap` is empty.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use tokio_util::task::JoinMap;
|
||||
///
|
||||
/// # #[tokio::main(flavor = "current_thread")]
|
||||
/// # async fn main() {
|
||||
/// let mut map = JoinMap::new();
|
||||
/// map.spawn("answer", async { 42 });
|
||||
///
|
||||
/// let (key, res) = loop {
|
||||
/// if let Some(joined) = map.try_join_next() {
|
||||
/// break joined;
|
||||
/// }
|
||||
/// tokio::task::yield_now().await;
|
||||
/// };
|
||||
///
|
||||
/// assert_eq!(key, "answer");
|
||||
/// assert_eq!(res.unwrap(), 42);
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn try_join_next(&mut self) -> Option<(K, Result<V, JoinError>)> {
|
||||
loop {
|
||||
let (res, id) = match self.tasks.try_join_next_with_id()? {
|
||||
Ok((id, output)) => (Ok(output), id),
|
||||
Err(e) => {
|
||||
let id = e.id();
|
||||
(Err(e), id)
|
||||
}
|
||||
};
|
||||
if let Some(key) = self.remove_by_id(id) {
|
||||
break Some((key, res));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Aborts all tasks and waits for them to finish shutting down.
|
||||
///
|
||||
/// Calling this method is equivalent to calling [`abort_all`] and then calling [`join_next`] in
|
||||
/// a loop until it returns `None`.
|
||||
///
|
||||
/// This method ignores any panics in the tasks shutting down. When this call returns, the
|
||||
/// `JoinMap` will be empty.
|
||||
///
|
||||
/// [`abort_all`]: fn@Self::abort_all
|
||||
/// [`join_next`]: fn@Self::join_next
|
||||
pub async fn shutdown(&mut self) {
|
||||
self.abort_all();
|
||||
while self.join_next().await.is_some() {}
|
||||
}
|
||||
|
||||
/// Abort the task corresponding to the provided `key`.
|
||||
///
|
||||
/// If this `JoinMap` contains a task corresponding to `key`, this method
|
||||
/// will abort that task and return `true`. Otherwise, if no task exists for
|
||||
/// `key`, this method returns `false`.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Aborting a task by key:
|
||||
///
|
||||
/// ```
|
||||
/// use tokio_util::task::JoinMap;
|
||||
///
|
||||
/// # #[tokio::main(flavor = "current_thread")]
|
||||
/// # async fn main() {
|
||||
/// let mut map = JoinMap::new();
|
||||
///
|
||||
/// map.spawn("hello world", std::future::ready(1));
|
||||
/// map.spawn("goodbye world", std::future::pending());
|
||||
///
|
||||
/// // Look up the "goodbye world" task in the map and abort it.
|
||||
/// map.abort("goodbye world");
|
||||
///
|
||||
/// while let Some((key, res)) = map.join_next().await {
|
||||
/// if key == "goodbye world" {
|
||||
/// // The aborted task should complete with a cancelled `JoinError`.
|
||||
/// assert!(res.unwrap_err().is_cancelled());
|
||||
/// } else {
|
||||
/// // Other tasks should complete normally.
|
||||
/// assert_eq!(res.unwrap(), 1);
|
||||
/// }
|
||||
/// }
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// `abort` returns `true` if a task was aborted:
|
||||
/// ```
|
||||
/// use tokio_util::task::JoinMap;
|
||||
///
|
||||
/// # #[tokio::main(flavor = "current_thread")]
|
||||
/// # async fn main() {
|
||||
/// let mut map = JoinMap::new();
|
||||
///
|
||||
/// map.spawn("hello world", async move { /* ... */ });
|
||||
/// map.spawn("goodbye world", async move { /* ... */});
|
||||
///
|
||||
/// // A task for the key "goodbye world" should exist in the map:
|
||||
/// assert!(map.abort("goodbye world"));
|
||||
///
|
||||
/// // Aborting a key that does not exist will return `false`:
|
||||
/// assert!(!map.abort("goodbye universe"));
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn abort<Q>(&mut self, key: &Q) -> bool
|
||||
where
|
||||
Q: ?Sized + Hash + Eq,
|
||||
K: Borrow<Q>,
|
||||
{
|
||||
match self.get_by_key(key) {
|
||||
Some((_, handle)) => {
|
||||
handle.abort();
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Aborts all tasks with keys matching `predicate`.
|
||||
///
|
||||
/// `predicate` is a function called with a reference to each key in the
|
||||
/// map. If it returns `true` for a given key, the corresponding task will
|
||||
/// be cancelled.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use tokio_util::task::JoinMap;
|
||||
///
|
||||
/// # // use the current thread rt so that spawned tasks don't
|
||||
/// # // complete in the background before they can be aborted.
|
||||
/// # #[tokio::main(flavor = "current_thread")]
|
||||
/// # async fn main() {
|
||||
/// let mut map = JoinMap::new();
|
||||
///
|
||||
/// map.spawn("hello world", async move {
|
||||
/// // ...
|
||||
/// # tokio::task::yield_now().await; // don't complete immediately, get aborted!
|
||||
/// });
|
||||
/// map.spawn("goodbye world", async move {
|
||||
/// // ...
|
||||
/// # tokio::task::yield_now().await; // don't complete immediately, get aborted!
|
||||
/// });
|
||||
/// map.spawn("hello san francisco", async move {
|
||||
/// // ...
|
||||
/// # tokio::task::yield_now().await; // don't complete immediately, get aborted!
|
||||
/// });
|
||||
/// map.spawn("goodbye universe", async move {
|
||||
/// // ...
|
||||
/// # tokio::task::yield_now().await; // don't complete immediately, get aborted!
|
||||
/// });
|
||||
///
|
||||
/// // Abort all tasks whose keys begin with "goodbye"
|
||||
/// map.abort_matching(|key| key.starts_with("goodbye"));
|
||||
///
|
||||
/// let mut seen = 0;
|
||||
/// while let Some((key, res)) = map.join_next().await {
|
||||
/// seen += 1;
|
||||
/// if key.starts_with("goodbye") {
|
||||
/// // The aborted task should complete with a cancelled `JoinError`.
|
||||
/// assert!(res.unwrap_err().is_cancelled());
|
||||
/// } else {
|
||||
/// // Other tasks should complete normally.
|
||||
/// assert!(key.starts_with("hello"));
|
||||
/// assert!(res.is_ok());
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // All spawned tasks should have completed.
|
||||
/// assert_eq!(seen, 4);
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn abort_matching(&mut self, mut predicate: impl FnMut(&K) -> bool) {
|
||||
// Note: this method iterates over the tasks and keys *without* removing
|
||||
// any entries, so that the keys from aborted tasks can still be
|
||||
// returned when calling `join_next` in the future.
|
||||
for (key, task) in &self.tasks_by_key {
|
||||
if predicate(key) {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an iterator visiting all keys in this `JoinMap` in arbitrary order.
|
||||
///
|
||||
/// If a task has completed, but its output hasn't yet been consumed by a
|
||||
/// call to [`join_next`], this method will still return its key.
|
||||
///
|
||||
/// [`join_next`]: fn@Self::join_next
|
||||
pub fn keys(&self) -> JoinMapKeys<'_, K, V> {
|
||||
JoinMapKeys {
|
||||
iter: self.tasks_by_key.iter(),
|
||||
_value: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if this `JoinMap` contains a task for the provided key.
|
||||
///
|
||||
/// If the task has completed, but its output hasn't yet been consumed by a
|
||||
/// call to [`join_next`], this method will still return `true`.
|
||||
///
|
||||
/// [`join_next`]: fn@Self::join_next
|
||||
pub fn contains_key<Q>(&self, key: &Q) -> bool
|
||||
where
|
||||
Q: ?Sized + Hash + Eq,
|
||||
K: Borrow<Q>,
|
||||
{
|
||||
self.get_by_key(key).is_some()
|
||||
}
|
||||
|
||||
/// Returns `true` if this `JoinMap` contains a task with the provided
|
||||
/// [task ID].
|
||||
///
|
||||
/// If the task has completed, but its output hasn't yet been consumed by a
|
||||
/// call to [`join_next`], this method will still return `true`.
|
||||
///
|
||||
/// [`join_next`]: fn@Self::join_next
|
||||
/// [task ID]: tokio::task::Id
|
||||
pub fn contains_task(&self, task: &Id) -> bool {
|
||||
self.hashes_by_task.contains_key(task)
|
||||
}
|
||||
|
||||
/// Reserves capacity for at least `additional` more tasks to be spawned
|
||||
/// on this `JoinMap` without reallocating for the map of task keys. The
|
||||
/// collection may reserve more space to avoid frequent reallocations.
|
||||
///
|
||||
/// Note that spawning a task will still cause an allocation for the task
|
||||
/// itself.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the new allocation size overflows [`usize`].
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use tokio_util::task::JoinMap;
|
||||
///
|
||||
/// let mut map: JoinMap<&str, i32> = JoinMap::new();
|
||||
/// map.reserve(10);
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn reserve(&mut self, additional: usize) {
|
||||
self.tasks_by_key.reserve(additional, |(k, _)| {
|
||||
self.hashes_by_task.hasher().hash_one(k)
|
||||
});
|
||||
self.hashes_by_task.reserve(additional);
|
||||
}
|
||||
|
||||
/// Shrinks the capacity of the `JoinMap` as much as possible. It will drop
|
||||
/// down as much as possible while maintaining the internal rules
|
||||
/// and possibly leaving some space in accordance with the resize policy.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// # #[tokio::main(flavor = "current_thread")]
|
||||
/// # async fn main() {
|
||||
/// use tokio_util::task::JoinMap;
|
||||
///
|
||||
/// let mut map: JoinMap<i32, i32> = JoinMap::with_capacity(100);
|
||||
/// map.spawn(1, async move { 2 });
|
||||
/// map.spawn(3, async move { 4 });
|
||||
/// assert!(map.capacity() >= 100);
|
||||
/// map.shrink_to_fit();
|
||||
/// assert!(map.capacity() >= 2);
|
||||
/// # }
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn shrink_to_fit(&mut self) {
|
||||
self.hashes_by_task.shrink_to_fit();
|
||||
self.tasks_by_key
|
||||
.shrink_to_fit(|(k, _)| self.hashes_by_task.hasher().hash_one(k));
|
||||
}
|
||||
|
||||
/// Shrinks the capacity of the map with a lower limit. It will drop
|
||||
/// down no lower than the supplied limit while maintaining the internal rules
|
||||
/// and possibly leaving some space in accordance with the resize policy.
|
||||
///
|
||||
/// If the current capacity is less than the lower limit, this is a no-op.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// # #[tokio::main(flavor = "current_thread")]
|
||||
/// # async fn main() {
|
||||
/// use tokio_util::task::JoinMap;
|
||||
///
|
||||
/// let mut map: JoinMap<i32, i32> = JoinMap::with_capacity(100);
|
||||
/// map.spawn(1, async move { 2 });
|
||||
/// map.spawn(3, async move { 4 });
|
||||
/// assert!(map.capacity() >= 100);
|
||||
/// map.shrink_to(10);
|
||||
/// assert!(map.capacity() >= 10);
|
||||
/// map.shrink_to(0);
|
||||
/// assert!(map.capacity() >= 2);
|
||||
/// # }
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn shrink_to(&mut self, min_capacity: usize) {
|
||||
self.hashes_by_task.shrink_to(min_capacity);
|
||||
self.tasks_by_key.shrink_to(min_capacity, |(k, _)| {
|
||||
self.hashes_by_task.hasher().hash_one(k)
|
||||
})
|
||||
}
|
||||
|
||||
/// Look up a task in the map by its key, returning the key and abort handle.
|
||||
fn get_by_key<'map, Q>(&'map self, key: &Q) -> Option<&'map (K, AbortHandle)>
|
||||
where
|
||||
Q: ?Sized + Hash + Eq,
|
||||
K: Borrow<Q>,
|
||||
{
|
||||
let hash = self.hashes_by_task.hasher().hash_one(key);
|
||||
self.tasks_by_key.find(hash, |(k, _)| k.borrow() == key)
|
||||
}
|
||||
|
||||
/// Remove a task from the map by ID, returning the key for that task.
|
||||
fn remove_by_id(&mut self, id: Id) -> Option<K> {
|
||||
// Get the hash for the given ID.
|
||||
let hash = self.hashes_by_task.remove(&id)?;
|
||||
|
||||
// Remove the entry for that hash.
|
||||
let entry = self
|
||||
.tasks_by_key
|
||||
.find_entry(hash, |(_, abort)| abort.id() == id);
|
||||
let (key, _) = match entry {
|
||||
Ok(entry) => entry.remove().0,
|
||||
_ => return None,
|
||||
};
|
||||
Some(key)
|
||||
}
|
||||
}
|
||||
|
||||
impl<K, V, S> JoinMap<K, V, S>
|
||||
where
|
||||
V: 'static,
|
||||
{
|
||||
/// Aborts all tasks on this `JoinMap`.
|
||||
///
|
||||
/// This does not remove the tasks from the `JoinMap`. To wait for the tasks to complete
|
||||
/// cancellation, you should call `join_next` in a loop until the `JoinMap` is empty.
|
||||
pub fn abort_all(&mut self) {
|
||||
self.tasks.abort_all()
|
||||
}
|
||||
|
||||
/// Removes all tasks from this `JoinMap` without aborting them.
|
||||
///
|
||||
/// The tasks removed by this call will continue to run in the background even if the `JoinMap`
|
||||
/// is dropped. They may still be aborted by key.
|
||||
pub fn detach_all(&mut self) {
|
||||
self.tasks.detach_all();
|
||||
self.tasks_by_key.clear();
|
||||
self.hashes_by_task.clear();
|
||||
}
|
||||
}
|
||||
|
||||
// Hand-written `fmt::Debug` implementation in order to avoid requiring `V:
|
||||
// Debug`, since no value is ever actually stored in the map.
|
||||
impl<K: fmt::Debug, V, S> fmt::Debug for JoinMap<K, V, S> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
// format the task keys and abort handles a little nicer by just
|
||||
// printing the key and task ID pairs, without format the `Key` struct
|
||||
// itself or the `AbortHandle`, which would just format the task's ID
|
||||
// again.
|
||||
struct KeySet<'a, K: fmt::Debug>(&'a HashTable<(K, AbortHandle)>);
|
||||
impl<K: fmt::Debug> fmt::Debug for KeySet<'_, K> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_map()
|
||||
.entries(self.0.iter().map(|(key, abort)| (key, abort.id())))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
f.debug_struct("JoinMap")
|
||||
// The `tasks_by_key` map is the only one that contains information
|
||||
// that's really worth formatting for the user, since it contains
|
||||
// the tasks' keys and IDs. The other fields are basically
|
||||
// implementation details.
|
||||
.field("tasks", &KeySet(&self.tasks_by_key))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<K, V> Default for JoinMap<K, V> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// An iterator over the keys of a [`JoinMap`].
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct JoinMapKeys<'a, K, V> {
|
||||
iter: hashbrown::hash_table::Iter<'a, (K, AbortHandle)>,
|
||||
/// To make it easier to change `JoinMap` in the future, keep V as a generic
|
||||
/// parameter.
|
||||
_value: PhantomData<&'a V>,
|
||||
}
|
||||
|
||||
impl<'a, K, V> Iterator for JoinMapKeys<'a, K, V> {
|
||||
type Item = &'a K;
|
||||
|
||||
fn next(&mut self) -> Option<&'a K> {
|
||||
self.iter.next().map(|(key, _)| key)
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
self.iter.size_hint()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, K, V> ExactSizeIterator for JoinMapKeys<'a, K, V> {
|
||||
fn len(&self) -> usize {
|
||||
self.iter.len()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, K, V> std::iter::FusedIterator for JoinMapKeys<'a, K, V> {}
|
||||
+429
@@ -0,0 +1,429 @@
|
||||
use super::AbortOnDropHandle;
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
future::Future,
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
use tokio::{
|
||||
runtime::Handle,
|
||||
task::{AbortHandle, Id, JoinError, JoinHandle},
|
||||
};
|
||||
|
||||
/// A FIFO queue for of tasks spawned on a Tokio runtime.
|
||||
///
|
||||
/// A [`JoinQueue`] can be used to await the completion of the tasks in FIFO
|
||||
/// order. That is, if tasks are spawned in the order A, B, C, then
|
||||
/// awaiting the next completed task will always return A first, then B,
|
||||
/// then C, regardless of the order in which the tasks actually complete.
|
||||
///
|
||||
/// All of the tasks must have the same return type `T`.
|
||||
///
|
||||
/// When the [`JoinQueue`] is dropped, all tasks in the [`JoinQueue`] are
|
||||
/// immediately aborted.
|
||||
pub struct JoinQueue<T>(VecDeque<AbortOnDropHandle<T>>);
|
||||
|
||||
impl<T> JoinQueue<T> {
|
||||
/// Create a new empty [`JoinQueue`].
|
||||
pub const fn new() -> Self {
|
||||
Self(VecDeque::new())
|
||||
}
|
||||
|
||||
/// Creates an empty [`JoinQueue`] with space for at least `capacity` tasks.
|
||||
pub fn with_capacity(capacity: usize) -> Self {
|
||||
Self(VecDeque::with_capacity(capacity))
|
||||
}
|
||||
|
||||
/// Returns the number of tasks currently in the [`JoinQueue`].
|
||||
///
|
||||
/// This includes both tasks that are currently running and tasks that have
|
||||
/// completed but not yet been removed from the queue because outputting of
|
||||
/// them waits for FIFO order.
|
||||
pub fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
|
||||
/// Returns whether the [`JoinQueue`] is empty.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
|
||||
/// Spawn the provided task on the [`JoinQueue`], returning an [`AbortHandle`]
|
||||
/// that can be used to remotely cancel the task.
|
||||
///
|
||||
/// The provided future will start running in the background immediately
|
||||
/// when this method is called, even if you don't await anything on this
|
||||
/// [`JoinQueue`].
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This method panics if called outside of a Tokio runtime.
|
||||
///
|
||||
/// [`AbortHandle`]: tokio::task::AbortHandle
|
||||
#[track_caller]
|
||||
pub fn spawn<F>(&mut self, task: F) -> AbortHandle
|
||||
where
|
||||
F: Future<Output = T> + Send + 'static,
|
||||
T: Send + 'static,
|
||||
{
|
||||
self.push_back(tokio::spawn(task))
|
||||
}
|
||||
|
||||
/// Spawn the provided task on the provided runtime and store it in this
|
||||
/// [`JoinQueue`] returning an [`AbortHandle`] that can be used to remotely
|
||||
/// cancel the task.
|
||||
///
|
||||
/// The provided future will start running in the background immediately
|
||||
/// when this method is called, even if you don't await anything on this
|
||||
/// [`JoinQueue`].
|
||||
///
|
||||
/// [`AbortHandle`]: tokio::task::AbortHandle
|
||||
#[track_caller]
|
||||
pub fn spawn_on<F>(&mut self, task: F, handle: &Handle) -> AbortHandle
|
||||
where
|
||||
F: Future<Output = T> + Send + 'static,
|
||||
T: Send + 'static,
|
||||
{
|
||||
self.push_back(handle.spawn(task))
|
||||
}
|
||||
|
||||
/// Spawn the provided task on the current [`LocalSet`] or [`LocalRuntime`]
|
||||
/// and store it in this [`JoinQueue`], returning an [`AbortHandle`] that
|
||||
/// can be used to remotely cancel the task.
|
||||
///
|
||||
/// The provided future will start running in the background immediately
|
||||
/// when this method is called, even if you don't await anything on this
|
||||
/// [`JoinQueue`].
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This method panics if it is called outside of a `LocalSet` or `LocalRuntime`.
|
||||
///
|
||||
/// [`LocalSet`]: tokio::task::LocalSet
|
||||
/// [`LocalRuntime`]: tokio::runtime::LocalRuntime
|
||||
/// [`AbortHandle`]: tokio::task::AbortHandle
|
||||
#[track_caller]
|
||||
pub fn spawn_local<F>(&mut self, task: F) -> AbortHandle
|
||||
where
|
||||
F: Future<Output = T> + 'static,
|
||||
T: 'static,
|
||||
{
|
||||
self.push_back(tokio::task::spawn_local(task))
|
||||
}
|
||||
|
||||
/// Spawn the blocking code on the blocking threadpool and store
|
||||
/// it in this [`JoinQueue`], returning an [`AbortHandle`] that can be
|
||||
/// used to remotely cancel the task.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This method panics if called outside of a Tokio runtime.
|
||||
///
|
||||
/// [`AbortHandle`]: tokio::task::AbortHandle
|
||||
#[track_caller]
|
||||
pub fn spawn_blocking<F>(&mut self, f: F) -> AbortHandle
|
||||
where
|
||||
F: FnOnce() -> T + Send + 'static,
|
||||
T: Send + 'static,
|
||||
{
|
||||
self.push_back(tokio::task::spawn_blocking(f))
|
||||
}
|
||||
|
||||
/// Spawn the blocking code on the blocking threadpool of the
|
||||
/// provided runtime and store it in this [`JoinQueue`], returning an
|
||||
/// [`AbortHandle`] that can be used to remotely cancel the task.
|
||||
///
|
||||
/// [`AbortHandle`]: tokio::task::AbortHandle
|
||||
#[track_caller]
|
||||
pub fn spawn_blocking_on<F>(&mut self, f: F, handle: &Handle) -> AbortHandle
|
||||
where
|
||||
F: FnOnce() -> T + Send + 'static,
|
||||
T: Send + 'static,
|
||||
{
|
||||
self.push_back(handle.spawn_blocking(f))
|
||||
}
|
||||
|
||||
fn push_back(&mut self, jh: JoinHandle<T>) -> AbortHandle {
|
||||
let jh = AbortOnDropHandle::new(jh);
|
||||
let abort_handle = jh.abort_handle();
|
||||
self.0.push_back(jh);
|
||||
abort_handle
|
||||
}
|
||||
|
||||
/// Waits until the next task in FIFO order completes and returns its output.
|
||||
///
|
||||
/// Returns `None` if the queue is empty.
|
||||
///
|
||||
/// # Cancel Safety
|
||||
///
|
||||
/// This method is cancel safe. If `join_next` is used as the event in a `tokio::select!`
|
||||
/// statement and some other branch completes first, it is guaranteed that no tasks were
|
||||
/// removed from this [`JoinQueue`].
|
||||
pub async fn join_next(&mut self) -> Option<Result<T, JoinError>> {
|
||||
std::future::poll_fn(|cx| self.poll_join_next(cx)).await
|
||||
}
|
||||
|
||||
/// Waits until the next task in FIFO order completes and returns its output,
|
||||
/// along with the [task ID] of the completed task.
|
||||
///
|
||||
/// Returns `None` if the queue is empty.
|
||||
///
|
||||
/// When this method returns an error, then the id of the task that failed can be accessed
|
||||
/// using the [`JoinError::id`] method.
|
||||
///
|
||||
/// # Cancel Safety
|
||||
///
|
||||
/// This method is cancel safe. If `join_next_with_id` is used as the event in a `tokio::select!`
|
||||
/// statement and some other branch completes first, it is guaranteed that no tasks were
|
||||
/// removed from this [`JoinQueue`].
|
||||
///
|
||||
/// [task ID]: tokio::task::Id
|
||||
/// [`JoinError::id`]: fn@tokio::task::JoinError::id
|
||||
pub async fn join_next_with_id(&mut self) -> Option<Result<(Id, T), JoinError>> {
|
||||
std::future::poll_fn(|cx| self.poll_join_next_with_id(cx)).await
|
||||
}
|
||||
|
||||
/// Tries to poll an `AbortOnDropHandle` without blocking or yielding.
|
||||
///
|
||||
/// Note that on success the handle will panic on subsequent polls
|
||||
/// since it becomes consumed.
|
||||
fn try_poll_handle(jh: &mut AbortOnDropHandle<T>) -> Option<Result<T, JoinError>> {
|
||||
if !jh.is_finished() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let waker = futures_util::task::noop_waker();
|
||||
let mut cx = Context::from_waker(&waker);
|
||||
|
||||
// Since this function is not async and cannot be forced to yield, we should
|
||||
// disable budgeting when we want to check for the `JoinHandle` readiness.
|
||||
let jh = std::pin::pin!(tokio::task::coop::unconstrained(jh));
|
||||
if let Poll::Ready(res) = jh.poll(&mut cx) {
|
||||
Some(res)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Tries to join the next task in FIFO order if it has completed.
|
||||
///
|
||||
/// Returns `None` if the queue is empty or if the next task is not yet ready.
|
||||
pub fn try_join_next(&mut self) -> Option<Result<T, JoinError>> {
|
||||
let jh = self.0.front_mut()?;
|
||||
let res = Self::try_poll_handle(jh)?;
|
||||
// Use `detach` to avoid calling `abort` on a task that has already completed.
|
||||
// Dropping `AbortOnDropHandle` would abort the task, but since it is finished,
|
||||
// we only need to drop the `JoinHandle` for cleanup.
|
||||
drop(self.0.pop_front().unwrap().detach());
|
||||
Some(res)
|
||||
}
|
||||
|
||||
/// Tries to join the next task in FIFO order if it has completed and return its output,
|
||||
/// along with its [task ID].
|
||||
///
|
||||
/// Returns `None` if the queue is empty or if the next task is not yet ready.
|
||||
///
|
||||
/// When this method returns an error, then the id of the task that failed can be accessed
|
||||
/// using the [`JoinError::id`] method.
|
||||
///
|
||||
/// [task ID]: tokio::task::Id
|
||||
/// [`JoinError::id`]: fn@tokio::task::JoinError::id
|
||||
pub fn try_join_next_with_id(&mut self) -> Option<Result<(Id, T), JoinError>> {
|
||||
let jh = self.0.front_mut()?;
|
||||
let res = Self::try_poll_handle(jh)?;
|
||||
// Use `detach` to avoid calling `abort` on a task that has already completed.
|
||||
// Dropping `AbortOnDropHandle` would abort the task, but since it is finished,
|
||||
// we only need to drop the `JoinHandle` for cleanup.
|
||||
let jh = self.0.pop_front().unwrap().detach();
|
||||
let id = jh.id();
|
||||
drop(jh);
|
||||
Some(res.map(|output| (id, output)))
|
||||
}
|
||||
|
||||
/// Aborts all tasks and waits for them to finish shutting down.
|
||||
///
|
||||
/// Calling this method is equivalent to calling [`abort_all`] and then calling [`join_next`] in
|
||||
/// a loop until it returns `None`.
|
||||
///
|
||||
/// This method ignores any panics in the tasks shutting down. When this call returns, the
|
||||
/// [`JoinQueue`] will be empty.
|
||||
///
|
||||
/// [`abort_all`]: fn@Self::abort_all
|
||||
/// [`join_next`]: fn@Self::join_next
|
||||
pub async fn shutdown(&mut self) {
|
||||
self.abort_all();
|
||||
while self.join_next().await.is_some() {}
|
||||
}
|
||||
|
||||
/// Awaits the completion of all tasks in this [`JoinQueue`], returning a vector of their results.
|
||||
///
|
||||
/// The results will be stored in the order they were spawned, not the order they completed.
|
||||
/// This is a convenience method that is equivalent to calling [`join_next`] in
|
||||
/// a loop. If any tasks on the [`JoinQueue`] fail with an [`JoinError`], then this call
|
||||
/// to `join_all` will panic and all remaining tasks on the [`JoinQueue`] are
|
||||
/// cancelled. To handle errors in any other way, manually call [`join_next`]
|
||||
/// in a loop.
|
||||
///
|
||||
/// # Cancel Safety
|
||||
///
|
||||
/// This method is not cancel safe as it calls `join_next` in a loop. If you need
|
||||
/// cancel safety, manually call `join_next` in a loop with `Vec` accumulator.
|
||||
///
|
||||
/// [`join_next`]: fn@Self::join_next
|
||||
/// [`JoinError::id`]: fn@tokio::task::JoinError::id
|
||||
pub async fn join_all(mut self) -> Vec<T> {
|
||||
let mut output = Vec::with_capacity(self.len());
|
||||
|
||||
while let Some(res) = self.join_next().await {
|
||||
match res {
|
||||
Ok(t) => output.push(t),
|
||||
Err(err) if err.is_panic() => std::panic::resume_unwind(err.into_panic()),
|
||||
Err(err) => panic!("{err}"),
|
||||
}
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
/// Aborts all tasks on this [`JoinQueue`].
|
||||
///
|
||||
/// This does not remove the tasks from the [`JoinQueue`]. To wait for the tasks to complete
|
||||
/// cancellation, you should call `join_next` in a loop until the [`JoinQueue`] is empty.
|
||||
pub fn abort_all(&mut self) {
|
||||
self.0.iter().for_each(|jh| jh.abort());
|
||||
}
|
||||
|
||||
/// Removes all tasks from this [`JoinQueue`] without aborting them.
|
||||
///
|
||||
/// The tasks removed by this call will continue to run in the background even if the [`JoinQueue`]
|
||||
/// is dropped.
|
||||
pub fn detach_all(&mut self) {
|
||||
self.0.drain(..).for_each(|jh| drop(jh.detach()));
|
||||
}
|
||||
|
||||
/// Polls for the next task in [`JoinQueue`] to complete.
|
||||
///
|
||||
/// If this returns `Poll::Ready(Some(_))`, then the task that completed is removed from the queue.
|
||||
///
|
||||
/// When the method returns `Poll::Pending`, the `Waker` in the provided `Context` is scheduled
|
||||
/// to receive a wakeup when a task in the [`JoinQueue`] completes. Note that on multiple calls to
|
||||
/// `poll_join_next`, only the `Waker` from the `Context` passed to the most recent call is
|
||||
/// scheduled to receive a wakeup.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// This function returns:
|
||||
///
|
||||
/// * `Poll::Pending` if the [`JoinQueue`] is not empty but there is no task whose output is
|
||||
/// available right now.
|
||||
/// * `Poll::Ready(Some(Ok(value)))` if the next task in this [`JoinQueue`] has completed.
|
||||
/// The `value` is the return value that task.
|
||||
/// * `Poll::Ready(Some(Err(err)))` if the next task in this [`JoinQueue`] has panicked or been
|
||||
/// aborted. The `err` is the `JoinError` from the panicked/aborted task.
|
||||
/// * `Poll::Ready(None)` if the [`JoinQueue`] is empty.
|
||||
pub fn poll_join_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<T, JoinError>>> {
|
||||
let jh = match self.0.front_mut() {
|
||||
None => return Poll::Ready(None),
|
||||
Some(jh) => jh,
|
||||
};
|
||||
if let Poll::Ready(res) = Pin::new(jh).poll(cx) {
|
||||
// Use `detach` to avoid calling `abort` on a task that has already completed.
|
||||
// Dropping `AbortOnDropHandle` would abort the task, but since it is finished,
|
||||
// we only need to drop the `JoinHandle` for cleanup.
|
||||
drop(self.0.pop_front().unwrap().detach());
|
||||
Poll::Ready(Some(res))
|
||||
} else {
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
/// Polls for the next task in [`JoinQueue`] to complete.
|
||||
///
|
||||
/// If this returns `Poll::Ready(Some(_))`, then the task that completed is removed from the queue.
|
||||
///
|
||||
/// When the method returns `Poll::Pending`, the `Waker` in the provided `Context` is scheduled
|
||||
/// to receive a wakeup when a task in the [`JoinQueue`] completes. Note that on multiple calls to
|
||||
/// `poll_join_next`, only the `Waker` from the `Context` passed to the most recent call is
|
||||
/// scheduled to receive a wakeup.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// This function returns:
|
||||
///
|
||||
/// * `Poll::Pending` if the [`JoinQueue`] is not empty but there is no task whose output is
|
||||
/// available right now.
|
||||
/// * `Poll::Ready(Some(Ok((id, value))))` if the next task in this [`JoinQueue`] has completed.
|
||||
/// The `value` is the return value that task, and `id` is its [task ID].
|
||||
/// * `Poll::Ready(Some(Err(err)))` if the next task in this [`JoinQueue`] has panicked or been
|
||||
/// aborted. The `err` is the `JoinError` from the panicked/aborted task.
|
||||
/// * `Poll::Ready(None)` if the [`JoinQueue`] is empty.
|
||||
///
|
||||
/// [task ID]: tokio::task::Id
|
||||
pub fn poll_join_next_with_id(
|
||||
&mut self,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<Option<Result<(Id, T), JoinError>>> {
|
||||
let jh = match self.0.front_mut() {
|
||||
None => return Poll::Ready(None),
|
||||
Some(jh) => jh,
|
||||
};
|
||||
if let Poll::Ready(res) = Pin::new(jh).poll(cx) {
|
||||
// Use `detach` to avoid calling `abort` on a task that has already completed.
|
||||
// Dropping `AbortOnDropHandle` would abort the task, but since it is finished,
|
||||
// we only need to drop the `JoinHandle` for cleanup.
|
||||
let jh = self.0.pop_front().unwrap().detach();
|
||||
let id = jh.id();
|
||||
drop(jh);
|
||||
// If the task succeeded, add the task ID to the output. Otherwise, the
|
||||
// `JoinError` will already have the task's ID.
|
||||
Poll::Ready(Some(res.map(|output| (id, output))))
|
||||
} else {
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> std::fmt::Debug for JoinQueue<T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_list()
|
||||
.entries(self.0.iter().map(|jh| JoinHandle::id(jh.as_ref())))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Default for JoinQueue<T> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Collect an iterator of futures into a [`JoinQueue`].
|
||||
///
|
||||
/// This is equivalent to calling [`JoinQueue::spawn`] on each element of the iterator.
|
||||
impl<T, F> std::iter::FromIterator<F> for JoinQueue<T>
|
||||
where
|
||||
F: Future<Output = T> + Send + 'static,
|
||||
T: Send + 'static,
|
||||
{
|
||||
fn from_iter<I: IntoIterator<Item = F>>(iter: I) -> Self {
|
||||
let mut set = Self::new();
|
||||
iter.into_iter().for_each(|task| {
|
||||
set.spawn(task);
|
||||
});
|
||||
set
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A simple type that does not implement [`std::fmt::Debug`].
|
||||
struct NotDebug;
|
||||
|
||||
fn is_debug<T: std::fmt::Debug>() {}
|
||||
|
||||
#[test]
|
||||
fn assert_debug() {
|
||||
is_debug::<JoinQueue<NotDebug>>();
|
||||
}
|
||||
}
|
||||
Vendored
+25
@@ -0,0 +1,25 @@
|
||||
//! Extra utilities for spawning tasks
|
||||
//!
|
||||
//! This module is only available when the `rt` feature is enabled. Note that enabling the
|
||||
//! `join-map` feature will automatically also enable the `rt` feature.
|
||||
|
||||
cfg_rt! {
|
||||
mod spawn_pinned;
|
||||
pub use spawn_pinned::LocalPoolHandle;
|
||||
|
||||
pub mod task_tracker;
|
||||
#[doc(inline)]
|
||||
pub use task_tracker::TaskTracker;
|
||||
|
||||
mod abort_on_drop;
|
||||
pub use abort_on_drop::{AbortOnDrop, AbortOnDropHandle};
|
||||
|
||||
mod join_queue;
|
||||
pub use join_queue::JoinQueue;
|
||||
}
|
||||
|
||||
#[cfg(feature = "join-map")]
|
||||
mod join_map;
|
||||
#[cfg(feature = "join-map")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "join-map")))]
|
||||
pub use join_map::{JoinMap, JoinMapKeys};
|
||||
+445
@@ -0,0 +1,445 @@
|
||||
use futures_util::future::{AbortHandle, Abortable};
|
||||
use std::fmt;
|
||||
use std::fmt::{Debug, Formatter};
|
||||
use std::future::Future;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use tokio::runtime::Builder;
|
||||
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::task::{spawn_local, JoinHandle, LocalSet};
|
||||
|
||||
/// A cloneable handle to a local pool, used for spawning `!Send` tasks.
|
||||
///
|
||||
/// Internally the local pool uses a [`tokio::task::LocalSet`] for each worker thread
|
||||
/// in the pool. Consequently you can also use [`tokio::task::spawn_local`] (which will
|
||||
/// execute on the same thread) inside the Future you supply to the various spawn methods
|
||||
/// of `LocalPoolHandle`.
|
||||
///
|
||||
/// [`tokio::task::LocalSet`]: tokio::task::LocalSet
|
||||
/// [`tokio::task::spawn_local`]: tokio::task::spawn_local
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// # #[cfg(not(target_family = "wasm"))]
|
||||
/// # {
|
||||
/// use std::rc::Rc;
|
||||
/// use tokio::task;
|
||||
/// use tokio_util::task::LocalPoolHandle;
|
||||
///
|
||||
/// #[tokio::main(flavor = "current_thread")]
|
||||
/// async fn main() {
|
||||
/// let pool = LocalPoolHandle::new(5);
|
||||
///
|
||||
/// let output = pool.spawn_pinned(|| {
|
||||
/// // `data` is !Send + !Sync
|
||||
/// let data = Rc::new("local data");
|
||||
/// let data_clone = data.clone();
|
||||
///
|
||||
/// async move {
|
||||
/// task::spawn_local(async move {
|
||||
/// println!("{}", data_clone);
|
||||
/// });
|
||||
///
|
||||
/// data.to_string()
|
||||
/// }
|
||||
/// }).await.unwrap();
|
||||
/// println!("output: {}", output);
|
||||
/// }
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
#[derive(Clone)]
|
||||
pub struct LocalPoolHandle {
|
||||
pool: Arc<LocalPool>,
|
||||
}
|
||||
|
||||
impl LocalPoolHandle {
|
||||
/// Create a new pool of threads to handle `!Send` tasks. Spawn tasks onto this
|
||||
/// pool via [`LocalPoolHandle::spawn_pinned`].
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the pool size is less than one.
|
||||
#[track_caller]
|
||||
pub fn new(pool_size: usize) -> LocalPoolHandle {
|
||||
assert!(pool_size > 0);
|
||||
|
||||
let workers = (0..pool_size)
|
||||
.map(|_| LocalWorkerHandle::new_worker())
|
||||
.collect();
|
||||
|
||||
let pool = Arc::new(LocalPool { workers });
|
||||
|
||||
LocalPoolHandle { pool }
|
||||
}
|
||||
|
||||
/// Returns the number of threads of the Pool.
|
||||
#[inline]
|
||||
pub fn num_threads(&self) -> usize {
|
||||
self.pool.workers.len()
|
||||
}
|
||||
|
||||
/// Returns the number of tasks scheduled on each worker. The indices of the
|
||||
/// worker threads correspond to the indices of the returned `Vec`.
|
||||
pub fn get_task_loads_for_each_worker(&self) -> Vec<usize> {
|
||||
self.pool
|
||||
.workers
|
||||
.iter()
|
||||
.map(|worker| worker.task_count.load(Ordering::SeqCst))
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
|
||||
/// Spawn a task onto a worker thread and pin it there so it can't be moved
|
||||
/// off of the thread. Note that the future is not [`Send`], but the
|
||||
/// [`FnOnce`] which creates it is.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// # #[cfg(not(target_family = "wasm"))]
|
||||
/// # {
|
||||
/// use std::rc::Rc;
|
||||
/// use tokio_util::task::LocalPoolHandle;
|
||||
///
|
||||
/// #[tokio::main]
|
||||
/// async fn main() {
|
||||
/// // Create the local pool
|
||||
/// let pool = LocalPoolHandle::new(1);
|
||||
///
|
||||
/// // Spawn a !Send future onto the pool and await it
|
||||
/// let output = pool
|
||||
/// .spawn_pinned(|| {
|
||||
/// // Rc is !Send + !Sync
|
||||
/// let local_data = Rc::new("test");
|
||||
///
|
||||
/// // This future holds an Rc, so it is !Send
|
||||
/// async move { local_data.to_string() }
|
||||
/// })
|
||||
/// .await
|
||||
/// .unwrap();
|
||||
///
|
||||
/// assert_eq!(output, "test");
|
||||
/// }
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn spawn_pinned<F, Fut>(&self, create_task: F) -> JoinHandle<Fut::Output>
|
||||
where
|
||||
F: FnOnce() -> Fut,
|
||||
F: Send + 'static,
|
||||
Fut: Future + 'static,
|
||||
Fut::Output: Send + 'static,
|
||||
{
|
||||
self.pool
|
||||
.spawn_pinned(create_task, WorkerChoice::LeastBurdened)
|
||||
}
|
||||
|
||||
/// Differs from `spawn_pinned` only in that you can choose a specific worker thread
|
||||
/// of the pool, whereas `spawn_pinned` chooses the worker with the smallest
|
||||
/// number of tasks scheduled.
|
||||
///
|
||||
/// A worker thread is chosen by index. Indices are 0 based and the largest index
|
||||
/// is given by `num_threads() - 1`
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This method panics if the index is out of bounds.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// This method can be used to spawn a task on all worker threads of the pool:
|
||||
///
|
||||
/// ```
|
||||
/// # #[cfg(not(target_family = "wasm"))]
|
||||
/// # {
|
||||
/// use tokio_util::task::LocalPoolHandle;
|
||||
///
|
||||
/// #[tokio::main]
|
||||
/// async fn main() {
|
||||
/// const NUM_WORKERS: usize = 3;
|
||||
/// let pool = LocalPoolHandle::new(NUM_WORKERS);
|
||||
/// let handles = (0..pool.num_threads())
|
||||
/// .map(|worker_idx| {
|
||||
/// pool.spawn_pinned_by_idx(
|
||||
/// || {
|
||||
/// async {
|
||||
/// "test"
|
||||
/// }
|
||||
/// },
|
||||
/// worker_idx,
|
||||
/// )
|
||||
/// })
|
||||
/// .collect::<Vec<_>>();
|
||||
///
|
||||
/// for handle in handles {
|
||||
/// handle.await.unwrap();
|
||||
/// }
|
||||
/// }
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
#[track_caller]
|
||||
pub fn spawn_pinned_by_idx<F, Fut>(&self, create_task: F, idx: usize) -> JoinHandle<Fut::Output>
|
||||
where
|
||||
F: FnOnce() -> Fut,
|
||||
F: Send + 'static,
|
||||
Fut: Future + 'static,
|
||||
Fut::Output: Send + 'static,
|
||||
{
|
||||
self.pool
|
||||
.spawn_pinned(create_task, WorkerChoice::ByIdx(idx))
|
||||
}
|
||||
}
|
||||
|
||||
impl Debug for LocalPoolHandle {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("LocalPoolHandle")
|
||||
}
|
||||
}
|
||||
|
||||
enum WorkerChoice {
|
||||
LeastBurdened,
|
||||
ByIdx(usize),
|
||||
}
|
||||
|
||||
struct LocalPool {
|
||||
workers: Box<[LocalWorkerHandle]>,
|
||||
}
|
||||
|
||||
impl LocalPool {
|
||||
/// Spawn a `?Send` future onto a worker
|
||||
#[track_caller]
|
||||
fn spawn_pinned<F, Fut>(
|
||||
&self,
|
||||
create_task: F,
|
||||
worker_choice: WorkerChoice,
|
||||
) -> JoinHandle<Fut::Output>
|
||||
where
|
||||
F: FnOnce() -> Fut,
|
||||
F: Send + 'static,
|
||||
Fut: Future + 'static,
|
||||
Fut::Output: Send + 'static,
|
||||
{
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
let (worker, job_guard) = match worker_choice {
|
||||
WorkerChoice::LeastBurdened => self.find_and_incr_least_burdened_worker(),
|
||||
WorkerChoice::ByIdx(idx) => self.find_worker_by_idx(idx),
|
||||
};
|
||||
let worker_spawner = worker.spawner.clone();
|
||||
|
||||
// Spawn a future onto the worker's runtime so we can immediately return
|
||||
// a join handle.
|
||||
worker.runtime_handle.spawn(async move {
|
||||
// Move the job guard into the task
|
||||
let _job_guard = job_guard;
|
||||
|
||||
// Propagate aborts via Abortable/AbortHandle
|
||||
let (abort_handle, abort_registration) = AbortHandle::new_pair();
|
||||
let _abort_guard = AbortGuard(abort_handle);
|
||||
|
||||
// Inside the future we can't run spawn_local yet because we're not
|
||||
// in the context of a LocalSet. We need to send create_task to the
|
||||
// LocalSet task for spawning.
|
||||
let spawn_task = Box::new(move || {
|
||||
// Once we're in the LocalSet context we can call spawn_local
|
||||
let join_handle =
|
||||
spawn_local(
|
||||
async move { Abortable::new(create_task(), abort_registration).await },
|
||||
);
|
||||
|
||||
// Send the join handle back to the spawner. If sending fails,
|
||||
// we assume the parent task was canceled, so cancel this task
|
||||
// as well.
|
||||
if let Err(join_handle) = sender.send(join_handle) {
|
||||
join_handle.abort()
|
||||
}
|
||||
});
|
||||
|
||||
// Send the callback to the LocalSet task
|
||||
if let Err(e) = worker_spawner.send(spawn_task) {
|
||||
// Propagate the error as a panic in the join handle.
|
||||
panic!("Failed to send job to worker: {e}");
|
||||
}
|
||||
|
||||
// Wait for the task's join handle
|
||||
let join_handle = match receiver.await {
|
||||
Ok(handle) => handle,
|
||||
Err(e) => {
|
||||
// We sent the task successfully, but failed to get its
|
||||
// join handle... We assume something happened to the worker
|
||||
// and the task was not spawned. Propagate the error as a
|
||||
// panic in the join handle.
|
||||
panic!("Worker failed to send join handle: {e}");
|
||||
}
|
||||
};
|
||||
|
||||
// Wait for the task to complete
|
||||
let join_result = join_handle.await;
|
||||
|
||||
match join_result {
|
||||
Ok(Ok(output)) => output,
|
||||
Ok(Err(_)) => {
|
||||
// Pinned task was aborted. But that only happens if this
|
||||
// task is aborted. So this is an impossible branch.
|
||||
unreachable!(
|
||||
"Reaching this branch means this task was previously \
|
||||
aborted but it continued running anyways"
|
||||
)
|
||||
}
|
||||
Err(e) => {
|
||||
if e.is_panic() {
|
||||
std::panic::resume_unwind(e.into_panic());
|
||||
} else if e.is_cancelled() {
|
||||
// No one else should have the join handle, so this is
|
||||
// unexpected. Forward this error as a panic in the join
|
||||
// handle.
|
||||
panic!("spawn_pinned task was canceled: {e}");
|
||||
} else {
|
||||
// Something unknown happened (not a panic or
|
||||
// cancellation). Forward this error as a panic in the
|
||||
// join handle.
|
||||
panic!("spawn_pinned task failed: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Find the worker with the least number of tasks, increment its task
|
||||
/// count, and return its handle. Make sure to actually spawn a task on
|
||||
/// the worker so the task count is kept consistent with load.
|
||||
///
|
||||
/// A job count guard is also returned to ensure the task count gets
|
||||
/// decremented when the job is done.
|
||||
fn find_and_incr_least_burdened_worker(&self) -> (&LocalWorkerHandle, JobCountGuard) {
|
||||
loop {
|
||||
let (worker, task_count) = self
|
||||
.workers
|
||||
.iter()
|
||||
.map(|worker| (worker, worker.task_count.load(Ordering::SeqCst)))
|
||||
.min_by_key(|&(_, count)| count)
|
||||
.expect("There must be more than one worker");
|
||||
|
||||
// Make sure the task count hasn't changed since when we choose this
|
||||
// worker. Otherwise, restart the search.
|
||||
if worker
|
||||
.task_count
|
||||
.compare_exchange(
|
||||
task_count,
|
||||
task_count + 1,
|
||||
Ordering::SeqCst,
|
||||
Ordering::Relaxed,
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
return (worker, JobCountGuard(Arc::clone(&worker.task_count)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn find_worker_by_idx(&self, idx: usize) -> (&LocalWorkerHandle, JobCountGuard) {
|
||||
let worker = &self.workers[idx];
|
||||
worker.task_count.fetch_add(1, Ordering::SeqCst);
|
||||
|
||||
(worker, JobCountGuard(Arc::clone(&worker.task_count)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Automatically decrements a worker's job count when a job finishes (when
|
||||
/// this gets dropped).
|
||||
struct JobCountGuard(Arc<AtomicUsize>);
|
||||
|
||||
impl Drop for JobCountGuard {
|
||||
fn drop(&mut self) {
|
||||
// Decrement the job count
|
||||
let previous_value = self.0.fetch_sub(1, Ordering::SeqCst);
|
||||
debug_assert!(previous_value >= 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls abort on the handle when dropped.
|
||||
struct AbortGuard(AbortHandle);
|
||||
|
||||
impl Drop for AbortGuard {
|
||||
fn drop(&mut self) {
|
||||
self.0.abort();
|
||||
}
|
||||
}
|
||||
|
||||
type PinnedFutureSpawner = Box<dyn FnOnce() + Send + 'static>;
|
||||
|
||||
struct LocalWorkerHandle {
|
||||
runtime_handle: tokio::runtime::Handle,
|
||||
spawner: UnboundedSender<PinnedFutureSpawner>,
|
||||
task_count: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
impl LocalWorkerHandle {
|
||||
/// Create a new worker for executing pinned tasks
|
||||
fn new_worker() -> LocalWorkerHandle {
|
||||
let (sender, receiver) = unbounded_channel();
|
||||
let runtime = Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("Failed to start a pinned worker thread runtime");
|
||||
let runtime_handle = runtime.handle().clone();
|
||||
let task_count = Arc::new(AtomicUsize::new(0));
|
||||
let task_count_clone = Arc::clone(&task_count);
|
||||
|
||||
std::thread::spawn(|| Self::run(runtime, receiver, task_count_clone));
|
||||
|
||||
LocalWorkerHandle {
|
||||
runtime_handle,
|
||||
spawner: sender,
|
||||
task_count,
|
||||
}
|
||||
}
|
||||
|
||||
fn run(
|
||||
runtime: tokio::runtime::Runtime,
|
||||
mut task_receiver: UnboundedReceiver<PinnedFutureSpawner>,
|
||||
task_count: Arc<AtomicUsize>,
|
||||
) {
|
||||
let local_set = LocalSet::new();
|
||||
local_set.block_on(&runtime, async {
|
||||
while let Some(spawn_task) = task_receiver.recv().await {
|
||||
// Calls spawn_local(future)
|
||||
(spawn_task)();
|
||||
}
|
||||
});
|
||||
|
||||
// If there are any tasks on the runtime associated with a LocalSet task
|
||||
// that has already completed, but whose output has not yet been
|
||||
// reported, let that task complete.
|
||||
//
|
||||
// Since the task_count is decremented when the runtime task exits,
|
||||
// reading that counter lets us know if any such tasks completed during
|
||||
// the call to `block_on`.
|
||||
//
|
||||
// Tasks on the LocalSet can't complete during this loop since they're
|
||||
// stored on the LocalSet and we aren't accessing it.
|
||||
let mut previous_task_count = task_count.load(Ordering::SeqCst);
|
||||
loop {
|
||||
// This call will also run tasks spawned on the runtime.
|
||||
runtime.block_on(tokio::task::yield_now());
|
||||
let new_task_count = task_count.load(Ordering::SeqCst);
|
||||
if new_task_count == previous_task_count {
|
||||
break;
|
||||
} else {
|
||||
previous_task_count = new_task_count;
|
||||
}
|
||||
}
|
||||
|
||||
// It's now no longer possible for a task on the runtime to be
|
||||
// associated with a LocalSet task that has completed. Drop both the
|
||||
// LocalSet and runtime to let tasks on the runtime be cancelled if and
|
||||
// only if they are still on the LocalSet.
|
||||
//
|
||||
// Drop the LocalSet task first so that anyone awaiting the runtime
|
||||
// JoinHandle will see the cancelled error after the LocalSet task
|
||||
// destructor has completed.
|
||||
drop(local_set);
|
||||
drop(runtime);
|
||||
}
|
||||
}
|
||||
+730
@@ -0,0 +1,730 @@
|
||||
//! Types related to the [`TaskTracker`] collection.
|
||||
//!
|
||||
//! See the documentation of [`TaskTracker`] for more information.
|
||||
|
||||
use pin_project_lite::pin_project;
|
||||
use std::fmt;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::task::{Context, Poll};
|
||||
use tokio::sync::{futures::Notified, Notify};
|
||||
|
||||
#[cfg(feature = "rt")]
|
||||
use tokio::{
|
||||
runtime::Handle,
|
||||
task::{JoinHandle, LocalSet},
|
||||
};
|
||||
|
||||
/// A task tracker used for waiting until tasks exit.
|
||||
///
|
||||
/// This is usually used together with [`CancellationToken`] to implement [graceful shutdown]. The
|
||||
/// `CancellationToken` is used to signal to tasks that they should shut down, and the
|
||||
/// `TaskTracker` is used to wait for them to finish shutting down.
|
||||
///
|
||||
/// The `TaskTracker` will also keep track of a `closed` boolean. This is used to handle the case
|
||||
/// where the `TaskTracker` is empty, but we don't want to shut down yet. This means that the
|
||||
/// [`wait`] method will wait until *both* of the following happen at the same time:
|
||||
///
|
||||
/// * The `TaskTracker` must be closed using the [`close`] method.
|
||||
/// * The `TaskTracker` must be empty, that is, all tasks that it is tracking must have exited.
|
||||
///
|
||||
/// When a call to [`wait`] returns, it is guaranteed that all tracked tasks have exited and that
|
||||
/// the destructor of the future has finished running. However, there might be a short amount of
|
||||
/// time where [`JoinHandle::is_finished`] returns false.
|
||||
///
|
||||
/// # Comparison to `JoinSet`
|
||||
///
|
||||
/// The main Tokio crate has a similar collection known as [`JoinSet`]. The `JoinSet` type has a
|
||||
/// lot more features than `TaskTracker`, so `TaskTracker` should only be used when one of its
|
||||
/// unique features is required:
|
||||
///
|
||||
/// 1. When tasks exit, a `TaskTracker` will allow the task to immediately free its memory.
|
||||
/// 2. By not closing the `TaskTracker`, [`wait`] will be prevented from returning even if
|
||||
/// the `TaskTracker` is empty.
|
||||
/// 3. A `TaskTracker` does not require mutable access to insert tasks.
|
||||
/// 4. A `TaskTracker` can be cloned to share it with many tasks.
|
||||
///
|
||||
/// The first point is the most important one. A [`JoinSet`] keeps track of the return value of
|
||||
/// every inserted task. This means that if the caller keeps inserting tasks and never calls
|
||||
/// [`join_next`], then their return values will keep building up and consuming memory, _even if_
|
||||
/// most of the tasks have already exited. This can cause the process to run out of memory. With a
|
||||
/// `TaskTracker`, this does not happen. Once tasks exit, they are immediately removed from the
|
||||
/// `TaskTracker`.
|
||||
///
|
||||
/// Note that unlike [`JoinSet`], dropping a `TaskTracker` does not abort the tasks.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// For more examples, please see the topic page on [graceful shutdown].
|
||||
///
|
||||
/// ## Spawn tasks and wait for them to exit
|
||||
///
|
||||
/// This is a simple example. For this case, [`JoinSet`] should probably be used instead.
|
||||
///
|
||||
/// ```
|
||||
/// use tokio_util::task::TaskTracker;
|
||||
///
|
||||
/// # #[tokio::main(flavor = "current_thread")]
|
||||
/// # async fn main() {
|
||||
/// let tracker = TaskTracker::new();
|
||||
///
|
||||
/// for i in 0..10 {
|
||||
/// tracker.spawn(async move {
|
||||
/// println!("Task {} is running!", i);
|
||||
/// });
|
||||
/// }
|
||||
/// // Once we spawned everything, we close the tracker.
|
||||
/// tracker.close();
|
||||
///
|
||||
/// // Wait for everything to finish.
|
||||
/// tracker.wait().await;
|
||||
///
|
||||
/// println!("This is printed after all of the tasks.");
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// ## Wait for tasks to exit
|
||||
///
|
||||
/// This example shows the intended use-case of `TaskTracker`. It is used together with
|
||||
/// [`CancellationToken`] to implement graceful shutdown.
|
||||
/// ```
|
||||
/// use tokio_util::sync::CancellationToken;
|
||||
/// use tokio_util::task::TaskTracker;
|
||||
/// use tokio_util::time::FutureExt;
|
||||
///
|
||||
/// use tokio::time::{self, Duration};
|
||||
///
|
||||
/// async fn background_task(num: u64) {
|
||||
/// for i in 0..10 {
|
||||
/// time::sleep(Duration::from_millis(100*num)).await;
|
||||
/// println!("Background task {} in iteration {}.", num, i);
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// #[tokio::main]
|
||||
/// # async fn _hidden() {}
|
||||
/// # #[tokio::main(flavor = "current_thread", start_paused = true)]
|
||||
/// async fn main() {
|
||||
/// let tracker = TaskTracker::new();
|
||||
/// let token = CancellationToken::new();
|
||||
///
|
||||
/// for i in 0..10 {
|
||||
/// let token = token.clone();
|
||||
/// tracker.spawn(async move {
|
||||
/// // Use a `with_cancellation_token_owned` to kill the background task
|
||||
/// // if the token is cancelled.
|
||||
/// match background_task(i)
|
||||
/// .with_cancellation_token_owned(token)
|
||||
/// .await
|
||||
/// {
|
||||
/// Some(()) => println!("Task {} exiting normally.", i),
|
||||
/// None => {
|
||||
/// // Do some cleanup before we really exit.
|
||||
/// time::sleep(Duration::from_millis(50)).await;
|
||||
/// println!("Task {} finished cleanup.", i);
|
||||
/// }
|
||||
/// }
|
||||
/// });
|
||||
/// }
|
||||
///
|
||||
/// // Spawn a background task that will send the shutdown signal.
|
||||
/// {
|
||||
/// let tracker = tracker.clone();
|
||||
/// tokio::spawn(async move {
|
||||
/// // Normally you would use something like ctrl-c instead of
|
||||
/// // sleeping.
|
||||
/// time::sleep(Duration::from_secs(2)).await;
|
||||
/// tracker.close();
|
||||
/// token.cancel();
|
||||
/// });
|
||||
/// }
|
||||
///
|
||||
/// // Wait for all tasks to exit.
|
||||
/// tracker.wait().await;
|
||||
///
|
||||
/// println!("All tasks have exited now.");
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// [`CancellationToken`]: crate::sync::CancellationToken
|
||||
/// [`JoinHandle::is_finished`]: tokio::task::JoinHandle::is_finished
|
||||
/// [`JoinSet`]: tokio::task::JoinSet
|
||||
/// [`close`]: Self::close
|
||||
/// [`join_next`]: tokio::task::JoinSet::join_next
|
||||
/// [`wait`]: Self::wait
|
||||
/// [graceful shutdown]: https://tokio.rs/tokio/topics/shutdown
|
||||
pub struct TaskTracker {
|
||||
inner: Arc<TaskTrackerInner>,
|
||||
}
|
||||
|
||||
/// Represents a task tracked by a [`TaskTracker`].
|
||||
#[must_use]
|
||||
#[derive(Debug)]
|
||||
pub struct TaskTrackerToken {
|
||||
task_tracker: TaskTracker,
|
||||
}
|
||||
|
||||
struct TaskTrackerInner {
|
||||
/// Keeps track of the state.
|
||||
///
|
||||
/// The lowest bit is whether the task tracker is closed.
|
||||
///
|
||||
/// The rest of the bits count the number of tracked tasks.
|
||||
state: AtomicUsize,
|
||||
/// Used to notify when the last task exits.
|
||||
on_last_exit: Notify,
|
||||
}
|
||||
|
||||
pin_project! {
|
||||
/// A future that is tracked as a task by a [`TaskTracker`].
|
||||
///
|
||||
/// The associated [`TaskTracker`] cannot complete until this future is dropped.
|
||||
///
|
||||
/// This future is returned by [`TaskTracker::track_future`].
|
||||
#[must_use = "futures do nothing unless polled"]
|
||||
pub struct TrackedFuture<F> {
|
||||
#[pin]
|
||||
future: F,
|
||||
token: TaskTrackerToken,
|
||||
}
|
||||
}
|
||||
|
||||
pin_project! {
|
||||
/// A future that completes when the [`TaskTracker`] is empty and closed.
|
||||
///
|
||||
/// This future is returned by [`TaskTracker::wait`].
|
||||
#[must_use = "futures do nothing unless polled"]
|
||||
pub struct TaskTrackerWaitFuture<'a> {
|
||||
#[pin]
|
||||
future: Notified<'a>,
|
||||
inner: Option<&'a TaskTrackerInner>,
|
||||
}
|
||||
}
|
||||
|
||||
impl TaskTrackerInner {
|
||||
#[inline]
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
state: AtomicUsize::new(0),
|
||||
on_last_exit: Notify::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_closed_and_empty(&self) -> bool {
|
||||
// If empty and closed bit set, then we are done.
|
||||
//
|
||||
// The acquire load will synchronize with the release store of any previous call to
|
||||
// `set_closed` and `drop_task`.
|
||||
self.state.load(Ordering::Acquire) == 1
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_closed(&self) -> bool {
|
||||
// The AcqRel ordering makes the closed bit behave like a `Mutex<bool>` for synchronization
|
||||
// purposes. We do this because it makes the return value of `TaskTracker::{close,reopen}`
|
||||
// more meaningful for the user. Without these orderings, this assert could fail:
|
||||
// ```
|
||||
// // thread 1
|
||||
// some_other_atomic.store(true, Relaxed);
|
||||
// tracker.close();
|
||||
//
|
||||
// // thread 2
|
||||
// if tracker.reopen() {
|
||||
// assert!(some_other_atomic.load(Relaxed));
|
||||
// }
|
||||
// ```
|
||||
// However, with the AcqRel ordering, we establish a happens-before relationship from the
|
||||
// call to `close` and the later call to `reopen` that returned true.
|
||||
let state = self.state.fetch_or(1, Ordering::AcqRel);
|
||||
|
||||
// If there are no tasks, and if it was not already closed:
|
||||
if state == 0 {
|
||||
self.notify_now();
|
||||
}
|
||||
|
||||
(state & 1) == 0
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_open(&self) -> bool {
|
||||
// See `set_closed` regarding the AcqRel ordering.
|
||||
let state = self.state.fetch_and(!1, Ordering::AcqRel);
|
||||
(state & 1) == 1
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn add_task(&self) {
|
||||
self.state.fetch_add(2, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn drop_task(&self) {
|
||||
let state = self.state.fetch_sub(2, Ordering::Release);
|
||||
|
||||
// If this was the last task and we are closed:
|
||||
if state == 3 {
|
||||
self.notify_now();
|
||||
}
|
||||
}
|
||||
|
||||
#[cold]
|
||||
fn notify_now(&self) {
|
||||
// Insert an acquire fence. This matters for `drop_task` but doesn't matter for
|
||||
// `set_closed` since it already uses AcqRel.
|
||||
//
|
||||
// This synchronizes with the release store of any other call to `drop_task`, and with the
|
||||
// release store in the call to `set_closed`. That ensures that everything that happened
|
||||
// before those other calls to `drop_task` or `set_closed` will be visible after this load,
|
||||
// and those things will also be visible to anything woken by the call to `notify_waiters`.
|
||||
self.state.load(Ordering::Acquire);
|
||||
|
||||
self.on_last_exit.notify_waiters();
|
||||
}
|
||||
}
|
||||
|
||||
impl TaskTracker {
|
||||
/// Creates a new `TaskTracker`.
|
||||
///
|
||||
/// The `TaskTracker` will start out as open.
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
inner: Arc::new(TaskTrackerInner::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits until this `TaskTracker` is both closed and empty.
|
||||
///
|
||||
/// If the `TaskTracker` is already closed and empty when this method is called, then it
|
||||
/// returns immediately.
|
||||
///
|
||||
/// The `wait` future is resistant against [ABA problems][aba]. That is, if the `TaskTracker`
|
||||
/// becomes both closed and empty for a short amount of time, then it is guarantee that all
|
||||
/// `wait` futures that were created before the short time interval will trigger, even if they
|
||||
/// are not polled during that short time interval.
|
||||
///
|
||||
/// # Cancel safety
|
||||
///
|
||||
/// This method is cancel safe.
|
||||
///
|
||||
/// However, the resistance against [ABA problems][aba] is lost when using `wait` as the
|
||||
/// condition in a `tokio::select!` loop.
|
||||
///
|
||||
/// [aba]: https://en.wikipedia.org/wiki/ABA_problem
|
||||
#[inline]
|
||||
pub fn wait(&self) -> TaskTrackerWaitFuture<'_> {
|
||||
TaskTrackerWaitFuture {
|
||||
future: self.inner.on_last_exit.notified(),
|
||||
inner: if self.inner.is_closed_and_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(&self.inner)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Close this `TaskTracker`.
|
||||
///
|
||||
/// This allows [`wait`] futures to complete. It does not prevent you from spawning new tasks.
|
||||
///
|
||||
/// Returns `true` if this closed the `TaskTracker`, or `false` if it was already closed.
|
||||
///
|
||||
/// [`wait`]: Self::wait
|
||||
#[inline]
|
||||
pub fn close(&self) -> bool {
|
||||
self.inner.set_closed()
|
||||
}
|
||||
|
||||
/// Reopen this `TaskTracker`.
|
||||
///
|
||||
/// This prevents [`wait`] futures from completing even if the `TaskTracker` is empty.
|
||||
///
|
||||
/// Returns `true` if this reopened the `TaskTracker`, or `false` if it was already open.
|
||||
///
|
||||
/// [`wait`]: Self::wait
|
||||
#[inline]
|
||||
pub fn reopen(&self) -> bool {
|
||||
self.inner.set_open()
|
||||
}
|
||||
|
||||
/// Returns `true` if this `TaskTracker` is [closed](Self::close).
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn is_closed(&self) -> bool {
|
||||
(self.inner.state.load(Ordering::Acquire) & 1) != 0
|
||||
}
|
||||
|
||||
/// Returns the number of tasks tracked by this `TaskTracker`.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn len(&self) -> usize {
|
||||
self.inner.state.load(Ordering::Acquire) >> 1
|
||||
}
|
||||
|
||||
/// Returns `true` if there are no tasks in this `TaskTracker`.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.inner.state.load(Ordering::Acquire) <= 1
|
||||
}
|
||||
|
||||
/// Spawn the provided future on the current Tokio runtime, and track it in this `TaskTracker`.
|
||||
///
|
||||
/// This is equivalent to `tokio::spawn(tracker.track_future(task))`.
|
||||
#[inline]
|
||||
#[track_caller]
|
||||
#[cfg(feature = "rt")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "rt")))]
|
||||
pub fn spawn<F>(&self, task: F) -> JoinHandle<F::Output>
|
||||
where
|
||||
F: Future + Send + 'static,
|
||||
F::Output: Send + 'static,
|
||||
{
|
||||
tokio::task::spawn(self.track_future(task))
|
||||
}
|
||||
|
||||
/// Spawn the provided future on the provided Tokio runtime, and track it in this `TaskTracker`.
|
||||
///
|
||||
/// This is equivalent to `handle.spawn(tracker.track_future(task))`.
|
||||
#[inline]
|
||||
#[track_caller]
|
||||
#[cfg(feature = "rt")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "rt")))]
|
||||
pub fn spawn_on<F>(&self, task: F, handle: &Handle) -> JoinHandle<F::Output>
|
||||
where
|
||||
F: Future + Send + 'static,
|
||||
F::Output: Send + 'static,
|
||||
{
|
||||
handle.spawn(self.track_future(task))
|
||||
}
|
||||
|
||||
/// Spawn the provided future on the current [`LocalSet`] or [`LocalRuntime`]
|
||||
/// and track it in this `TaskTracker`.
|
||||
///
|
||||
/// This is equivalent to `tokio::task::spawn_local(tracker.track_future(task))`.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This method panics if it is called outside of a `LocalSet` or `LocalRuntime`.
|
||||
///
|
||||
/// [`LocalSet`]: tokio::task::LocalSet
|
||||
/// [`LocalRuntime`]: tokio::runtime::LocalRuntime
|
||||
#[inline]
|
||||
#[track_caller]
|
||||
#[cfg(feature = "rt")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "rt")))]
|
||||
pub fn spawn_local<F>(&self, task: F) -> JoinHandle<F::Output>
|
||||
where
|
||||
F: Future + 'static,
|
||||
F::Output: 'static,
|
||||
{
|
||||
tokio::task::spawn_local(self.track_future(task))
|
||||
}
|
||||
|
||||
/// Spawn the provided future on the provided [`LocalSet`], and track it in this `TaskTracker`.
|
||||
///
|
||||
/// This is equivalent to `local_set.spawn_local(tracker.track_future(task))`.
|
||||
///
|
||||
/// [`LocalSet`]: tokio::task::LocalSet
|
||||
#[inline]
|
||||
#[track_caller]
|
||||
#[cfg(feature = "rt")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "rt")))]
|
||||
pub fn spawn_local_on<F>(&self, task: F, local_set: &LocalSet) -> JoinHandle<F::Output>
|
||||
where
|
||||
F: Future + 'static,
|
||||
F::Output: 'static,
|
||||
{
|
||||
local_set.spawn_local(self.track_future(task))
|
||||
}
|
||||
|
||||
/// Spawn the provided blocking task on the current Tokio runtime, and track it in this `TaskTracker`.
|
||||
///
|
||||
/// This is equivalent to `tokio::task::spawn_blocking(tracker.track_future(task))`.
|
||||
#[inline]
|
||||
#[track_caller]
|
||||
#[cfg(feature = "rt")]
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "rt")))]
|
||||
pub fn spawn_blocking<F, T>(&self, task: F) -> JoinHandle<T>
|
||||
where
|
||||
F: FnOnce() -> T,
|
||||
F: Send + 'static,
|
||||
T: Send + 'static,
|
||||
{
|
||||
let token = self.token();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let res = task();
|
||||
drop(token);
|
||||
res
|
||||
})
|
||||
}
|
||||
|
||||
/// Spawn the provided blocking task on the provided Tokio runtime, and track it in this `TaskTracker`.
|
||||
///
|
||||
/// This is equivalent to `handle.spawn_blocking(tracker.track_future(task))`.
|
||||
#[inline]
|
||||
#[track_caller]
|
||||
#[cfg(feature = "rt")]
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "rt")))]
|
||||
pub fn spawn_blocking_on<F, T>(&self, task: F, handle: &Handle) -> JoinHandle<T>
|
||||
where
|
||||
F: FnOnce() -> T,
|
||||
F: Send + 'static,
|
||||
T: Send + 'static,
|
||||
{
|
||||
let token = self.token();
|
||||
handle.spawn_blocking(move || {
|
||||
let res = task();
|
||||
drop(token);
|
||||
res
|
||||
})
|
||||
}
|
||||
|
||||
/// Track the provided future.
|
||||
///
|
||||
/// The returned [`TrackedFuture`] will count as a task tracked by this collection, and will
|
||||
/// prevent calls to [`wait`] from returning until the task is dropped.
|
||||
///
|
||||
/// The task is removed from the collection when it is dropped, not when [`poll`] returns
|
||||
/// [`Poll::Ready`].
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Track a future spawned with [`tokio::spawn`].
|
||||
///
|
||||
/// ```
|
||||
/// # async fn my_async_fn() {}
|
||||
/// use tokio_util::task::TaskTracker;
|
||||
///
|
||||
/// # #[tokio::main(flavor = "current_thread")]
|
||||
/// # async fn main() {
|
||||
/// let tracker = TaskTracker::new();
|
||||
///
|
||||
/// tokio::spawn(tracker.track_future(my_async_fn()));
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// Track a future spawned on a [`JoinSet`].
|
||||
/// ```
|
||||
/// # async fn my_async_fn() {}
|
||||
/// use tokio::task::JoinSet;
|
||||
/// use tokio_util::task::TaskTracker;
|
||||
///
|
||||
/// # #[tokio::main(flavor = "current_thread")]
|
||||
/// # async fn main() {
|
||||
/// let tracker = TaskTracker::new();
|
||||
/// let mut join_set = JoinSet::new();
|
||||
///
|
||||
/// join_set.spawn(tracker.track_future(my_async_fn()));
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// [`JoinSet`]: tokio::task::JoinSet
|
||||
/// [`Poll::Pending`]: std::task::Poll::Pending
|
||||
/// [`poll`]: std::future::Future::poll
|
||||
/// [`wait`]: Self::wait
|
||||
#[inline]
|
||||
pub fn track_future<F: Future>(&self, future: F) -> TrackedFuture<F> {
|
||||
TrackedFuture {
|
||||
future,
|
||||
token: self.token(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a [`TaskTrackerToken`] representing a task tracked by this `TaskTracker`.
|
||||
///
|
||||
/// This token is a lower-level utility than the spawn methods. Each token is considered to
|
||||
/// correspond to a task. As long as the token exists, the `TaskTracker` cannot complete.
|
||||
/// Furthermore, the count returned by the [`len`] method will include the tokens in the count.
|
||||
///
|
||||
/// Dropping the token indicates to the `TaskTracker` that the task has exited.
|
||||
///
|
||||
/// [`len`]: TaskTracker::len
|
||||
#[inline]
|
||||
pub fn token(&self) -> TaskTrackerToken {
|
||||
self.inner.add_task();
|
||||
TaskTrackerToken {
|
||||
task_tracker: self.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if both task trackers correspond to the same set of tasks.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use tokio_util::task::TaskTracker;
|
||||
///
|
||||
/// let tracker_1 = TaskTracker::new();
|
||||
/// let tracker_2 = TaskTracker::new();
|
||||
/// let tracker_1_clone = tracker_1.clone();
|
||||
///
|
||||
/// assert!(TaskTracker::ptr_eq(&tracker_1, &tracker_1_clone));
|
||||
/// assert!(!TaskTracker::ptr_eq(&tracker_1, &tracker_2));
|
||||
/// ```
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn ptr_eq(left: &TaskTracker, right: &TaskTracker) -> bool {
|
||||
Arc::ptr_eq(&left.inner, &right.inner)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for TaskTracker {
|
||||
/// Creates a new `TaskTracker`.
|
||||
///
|
||||
/// The `TaskTracker` will start out as open.
|
||||
#[inline]
|
||||
fn default() -> TaskTracker {
|
||||
TaskTracker::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for TaskTracker {
|
||||
/// Returns a new `TaskTracker` that tracks the same set of tasks.
|
||||
///
|
||||
/// Since the new `TaskTracker` shares the same set of tasks, changes to one set are visible in
|
||||
/// all other clones.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use tokio_util::task::TaskTracker;
|
||||
///
|
||||
/// #[tokio::main]
|
||||
/// # async fn _hidden() {}
|
||||
/// # #[tokio::main(flavor = "current_thread")]
|
||||
/// async fn main() {
|
||||
/// let tracker = TaskTracker::new();
|
||||
/// let cloned = tracker.clone();
|
||||
///
|
||||
/// // Spawns on `tracker` are visible in `cloned`.
|
||||
/// tracker.spawn(std::future::pending::<()>());
|
||||
/// assert_eq!(cloned.len(), 1);
|
||||
///
|
||||
/// // Spawns on `cloned` are visible in `tracker`.
|
||||
/// cloned.spawn(std::future::pending::<()>());
|
||||
/// assert_eq!(tracker.len(), 2);
|
||||
///
|
||||
/// // Calling `close` is visible to `cloned`.
|
||||
/// tracker.close();
|
||||
/// assert!(cloned.is_closed());
|
||||
///
|
||||
/// // Calling `reopen` is visible to `tracker`.
|
||||
/// cloned.reopen();
|
||||
/// assert!(!tracker.is_closed());
|
||||
/// }
|
||||
/// ```
|
||||
#[inline]
|
||||
fn clone(&self) -> TaskTracker {
|
||||
Self {
|
||||
inner: self.inner.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn debug_inner(inner: &TaskTrackerInner, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let state = inner.state.load(Ordering::Acquire);
|
||||
let is_closed = (state & 1) != 0;
|
||||
let len = state >> 1;
|
||||
|
||||
f.debug_struct("TaskTracker")
|
||||
.field("len", &len)
|
||||
.field("is_closed", &is_closed)
|
||||
.field("inner", &(inner as *const TaskTrackerInner))
|
||||
.finish()
|
||||
}
|
||||
|
||||
impl fmt::Debug for TaskTracker {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
debug_inner(&self.inner, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl TaskTrackerToken {
|
||||
/// Returns the [`TaskTracker`] that this token is associated with.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn task_tracker(&self) -> &TaskTracker {
|
||||
&self.task_tracker
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for TaskTrackerToken {
|
||||
/// Returns a new `TaskTrackerToken` associated with the same [`TaskTracker`].
|
||||
///
|
||||
/// This is equivalent to `token.task_tracker().token()`.
|
||||
#[inline]
|
||||
fn clone(&self) -> TaskTrackerToken {
|
||||
self.task_tracker.token()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TaskTrackerToken {
|
||||
/// Dropping the token indicates to the [`TaskTracker`] that the task has exited.
|
||||
#[inline]
|
||||
fn drop(&mut self) {
|
||||
self.task_tracker.inner.drop_task();
|
||||
}
|
||||
}
|
||||
|
||||
impl<F: Future> Future for TrackedFuture<F> {
|
||||
type Output = F::Output;
|
||||
|
||||
#[inline]
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<F::Output> {
|
||||
self.project().future.poll(cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl<F: fmt::Debug> fmt::Debug for TrackedFuture<F> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("TrackedFuture")
|
||||
.field("future", &self.future)
|
||||
.field("task_tracker", self.token.task_tracker())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Future for TaskTrackerWaitFuture<'a> {
|
||||
type Output = ();
|
||||
|
||||
#[inline]
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
|
||||
let me = self.project();
|
||||
|
||||
let inner = match me.inner.as_ref() {
|
||||
None => return Poll::Ready(()),
|
||||
Some(inner) => inner,
|
||||
};
|
||||
|
||||
let ready = inner.is_closed_and_empty() || me.future.poll(cx).is_ready();
|
||||
if ready {
|
||||
*me.inner = None;
|
||||
Poll::Ready(())
|
||||
} else {
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> fmt::Debug for TaskTrackerWaitFuture<'a> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
struct Helper<'a>(&'a TaskTrackerInner);
|
||||
|
||||
impl fmt::Debug for Helper<'_> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
debug_inner(self.0, f)
|
||||
}
|
||||
}
|
||||
|
||||
f.debug_struct("TaskTrackerWaitFuture")
|
||||
.field("future", &self.future)
|
||||
.field("task_tracker", &self.inner.map(Helper))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user