Skip to content

Commit

Permalink
spawn_blocking: Expand on cancellation a bit
Browse files Browse the repository at this point in the history
I was looking at these docs again and I was thinking the
"cannot be cancelled" is misleading; let's talk about approaches
to do so.
  • Loading branch information
cgwalters committed Jul 7, 2022
1 parent 4daeea8 commit 24bea90
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions tokio/src/task/blocking.rs
Expand Up @@ -102,11 +102,21 @@ cfg_rt! {
/// their own. If you want to spawn an ordinary thread, you should use
/// [`thread::spawn`] instead.
///
/// Closures spawned using `spawn_blocking` cannot be cancelled. When you shut
/// down the executor, it will wait indefinitely for all blocking operations to
/// Closures spawned using `spawn_blocking` cannot be cancelled abruptly; there
/// is no standard low level API to cause a thread to stop running. However,
/// a useful pattern is to pass some form of "cancellation token" into
/// the thread. This could be an [`AtomicBool`] that the task checks periodically.
/// Another approach is to have the thread primarily read or write from a channel,
/// and to exit when the channel closes; assuming the other side of the channel is dropped
/// when cancellation occurs, this will cause the blocking task thread to exit
/// soon after as well.
///
/// When you shut down the executor, it will wait indefinitely for all blocking operations to
/// finish. You can use [`shutdown_timeout`] to stop waiting for them after a
/// certain timeout. Be aware that this will still not cancel the tasks — they
/// are simply allowed to keep running after the method returns.
/// are simply allowed to keep running after the method returns. It is possible
/// for a blocking task to be cancelled if it has not yet started running, but this
/// is not guaranteed.
///
/// Note that if you are using the single threaded runtime, this function will
/// still spawn additional threads for blocking operations. The basic
Expand Down Expand Up @@ -140,6 +150,7 @@ cfg_rt! {
/// [`thread::spawn`]: fn@std::thread::spawn
/// [`shutdown_timeout`]: fn@crate::runtime::Runtime::shutdown_timeout
/// [bridgesync]: https://tokio.rs/tokio/topics/bridging
/// [`AtomicBool`]: https://doc.rust-lang.org/core/sync/atomic/struct.AtomicBool.html
///
/// # Examples
///
Expand Down

0 comments on commit 24bea90

Please sign in to comment.