From 7dd9ac1583f30fa35224f5389d911a0d0878c196 Mon Sep 17 00:00:00 2001 From: SparkyPotato Date: Mon, 13 Mar 2023 21:03:42 +0530 Subject: [PATCH] task: improve docs of `JoinHandle::abort_handle` --- tokio/src/runtime/task/join.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/tokio/src/runtime/task/join.rs b/tokio/src/runtime/task/join.rs index bb8623f18ae..2683f5e81bd 100644 --- a/tokio/src/runtime/task/join.rs +++ b/tokio/src/runtime/task/join.rs @@ -252,6 +252,40 @@ impl JoinHandle { } /// Returns a new `AbortHandle` that can be used to remotely abort this task. + /// + /// 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] + /// async fn main() { + /// 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> = 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)