Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

task: make JoinHandle::abort_handle public #5543

Merged
merged 5 commits into from Mar 16, 2023
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
44 changes: 40 additions & 4 deletions tokio/src/runtime/task/join.rs
Expand Up @@ -182,8 +182,9 @@ impl<T> JoinHandle<T> {
/// ```rust
/// use tokio::time;
///
/// #[tokio::main]
/// async fn main() {
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// # tokio::time::pause();
/// let mut handles = Vec::new();
///
/// handles.push(tokio::spawn(async {
Expand All @@ -203,7 +204,7 @@ impl<T> JoinHandle<T> {
/// for handle in handles {
/// assert!(handle.await.unwrap_err().is_cancelled());
/// }
/// }
/// # }
/// ```
/// [cancelled]: method@super::error::JoinError::is_cancelled
pub fn abort(&self) {
Expand Down Expand Up @@ -252,7 +253,42 @@ impl<T> JoinHandle<T> {
}

/// Returns a new `AbortHandle` that can be used to remotely abort this task.
pub(crate) fn abort_handle(&self) -> super::AbortHandle {
///
/// Awaiting a task cancelled by the `AbortHandle` might complete as usual if the task was
/// already completed at the time it was cancelled, but most likely it
/// will fail with a [cancelled] `JoinError`.
///
/// ```rust
/// use tokio::{time, task};
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// # time::pause();
SparkyPotato marked this conversation as resolved.
Show resolved Hide resolved
/// let mut handles = Vec::new();
///
/// handles.push(tokio::spawn(async {
/// time::sleep(time::Duration::from_secs(10)).await;
/// true
/// }));
///
/// handles.push(tokio::spawn(async {
/// time::sleep(time::Duration::from_secs(10)).await;
/// false
/// }));
///
/// let abort_handles: Vec<task::AbortHandle> = handles.iter().map(|h| h.abort_handle()).collect();
///
/// for handle in abort_handles {
/// handle.abort();
/// }
///
/// for handle in handles {
/// assert!(handle.await.unwrap_err().is_cancelled());
/// }
/// # }
/// ```
/// [cancelled]: method@super::error::JoinError::is_cancelled
pub fn abort_handle(&self) -> super::AbortHandle {
self.raw.ref_inc();
super::AbortHandle::new(self.raw)
}
Expand Down