diff options
author | John-John Tedro <udoprog@tedro.se> | 2020-09-09 05:52:57 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-09-08 20:52:57 -0700 |
commit | cbb14a7bb9a13363e1abee8caff2bad1f996c263 (patch) | |
tree | 1721a8efa56eb69eca318334124b66c5804eaa56 /tokio/src/runtime | |
parent | a0a356152e87f03ceb6f431f17405d8eb96cb069 (diff) |
sync: add JoinHandle::abort (#2474)
Diffstat (limited to 'tokio/src/runtime')
-rw-r--r-- | tokio/src/runtime/task/join.rs | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/tokio/src/runtime/task/join.rs b/tokio/src/runtime/task/join.rs index 0529aa29..ae776509 100644 --- a/tokio/src/runtime/task/join.rs +++ b/tokio/src/runtime/task/join.rs @@ -157,6 +157,44 @@ impl<T> JoinHandle<T> { _p: PhantomData, } } + + /// Abort the task associated with the handle. + /// + /// Awaiting a cancelled task might complete as usual if the task was + /// already completed at the time it was cancelled, but most likely it + /// will complete with a `Err(JoinError::Cancelled)`. + /// + /// ```rust + /// use tokio::time; + /// + /// #[tokio::main] + /// async fn main() { + /// let mut handles = Vec::new(); + /// + /// handles.push(tokio::spawn(async { + /// time::delay_for(time::Duration::from_secs(10)).await; + /// true + /// })); + /// + /// handles.push(tokio::spawn(async { + /// time::delay_for(time::Duration::from_secs(10)).await; + /// false + /// })); + /// + /// for handle in &handles { + /// handle.abort(); + /// } + /// + /// for handle in handles { + /// assert!(handle.await.unwrap_err().is_cancelled()); + /// } + /// } + /// ``` + pub fn abort(&self) { + if let Some(raw) = self.raw { + raw.shutdown(); + } + } } impl<T> Unpin for JoinHandle<T> {} |