AbortHandle type for cancelling tasks in a JoinSet (#4530)
## Motivation Before we stabilize the `JoinSet` API, we intend to add a method for individual tasks in the `JoinSet` to be aborted. Because the `JoinHandle`s for the tasks spawned on a `JoinSet` are owned by the `JoinSet`, the user can no longer use them to abort tasks on the `JoinSet`. Therefore, we need another way to cause a remote abort of a task on a `JoinSet` without holding its `JoinHandle`. ## Solution This branch adds a new `AbortHandle` type in `tokio::task`, which represents the owned permission to remotely cancel a task, but _not_ to await its output. The `AbortHandle` type holds an additional reference to the task cell. A crate-private method is added to `JoinHandle` that returns an `AbortHandle` for the same task, incrementing its ref count. `AbortHandle` provides a single method, `AbortHandle::abort(self)`, that remotely cancels the task. Dropping an `AbortHandle` decrements the task's ref count but does not cancel it. The `AbortHandle` type is currently marked as unstable. The spawning methods on `JoinSet` are modified to return an `AbortHandle` that can be used to cancel the spawned task. ## Future Work - Currently, the `AbortHandle` type is _only_ available in the public API through a `JoinSet`. We could also make the `JoinHandle::abort_handle` method public, to allow users to use the `AbortHandle` type in other contexts. I didn't do that in this PR, because I wanted to make the API addition as minimal as possible, but we could make this method public later. - Currently, `AbortHandle` is not `Clone`. We could easily make it `Clone` by incrementing the task's ref count. Since this adds more trait impls to the API, we may want to be cautious about this, but I see no obvious reason we would need to remove a `Clone` implementation if one was added... - There's been some discussion of adding a `JoinMap` type that allows aborting tasks by key, and manages a hash map of keys to `AbortHandle`s, and removes the tasks from the map when they complete. This would make aborting by key much easier, since the user wouldn't have to worry about keeping the state of the map of abort handles and the tasks actually active on the `JoinSet` in sync. After thinking about it a bit, I thought this is probably best as a `tokio-util` API --- it can currently be implemented in `tokio-util` with the APIs added in `tokio` in this PR. - I noticed while working on this that `JoinSet::join_one` and `JoinSet::poll_join_one` return a cancelled `JoinError` when a task is cancelled. I'm not sure if I love this behavior --- it seems like it would be nicer to just skip cancelled tasks and continue polling. But, there are currently tests that expect a cancelled `JoinError` to be returned for each cancelled task, so I didn't want to change it in _this_ PR. I think this is worth revisiting before stabilizing the API, though? Signed-off-by: Eliza Weisman <[email protected]>
Tokio
A runtime for writing reliable, asynchronous, and slim applications with the Rust programming language. It is:
-
Fast: Tokio's zero-cost abstractions give you bare-metal performance.
-
Reliable: Tokio leverages Rust's ownership, type system, and concurrency model to reduce bugs and ensure thread safety.
-
Scalable: Tokio has a minimal footprint, and handles backpressure and cancellation naturally.
Website | Guides | API Docs | Chat
Overview
Tokio is an event-driven, non-blocking I/O platform for writing asynchronous applications with the Rust programming language. At a high level, it provides a few major components:
- A multithreaded, work-stealing based task scheduler.
- A reactor backed by the operating system's event queue (epoll, kqueue, IOCP, etc...).
- Asynchronous TCP and UDP sockets.
These components provide the runtime components necessary for building an asynchronous application.
Example
A basic TCP echo server with Tokio.
Make sure you activated the full features of the tokio crate on Cargo.toml:
[dependencies]
tokio = { version = "1.17.0", features = ["full"] }
Then, on your main.rs:
use tokio::net::TcpListener;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let listener = TcpListener::bind("127.0.0.1:8080").await?;
loop {
let (mut socket, _) = listener.accept().await?;
tokio::spawn(async move {
let mut buf = [0; 1024];
// In a loop, read data from the socket and write the data back.
loop {
let n = match socket.read(&mut buf).await {
// socket closed
Ok(n) if n == 0 => return,
Ok(n) => n,
Err(e) => {
eprintln!("failed to read from socket; err = {:?}", e);
return;
}
};
// Write the data back
if let Err(e) = socket.write_all(&buf[0..n]).await {
eprintln!("failed to write to socket; err = {:?}", e);
return;
}
}
});
}
}
More examples can be found here. For a larger "real world" example, see the mini-redis repository.
To see a list of the available features flags that can be enabled, check our docs.
Getting Help
First, see if the answer to your question can be found in the Guides or the API documentation. If the answer is not there, there is an active community in the Tokio Discord server. We would be happy to try to answer your question. You can also ask your question on the discussions page.
Contributing
🎈 Thanks for your help improving the project! We are so happy to have you! We have a contributing guide to help you get involved in the Tokio project.
Related Projects
In addition to the crates in this repository, the Tokio project also maintains several other libraries, including:
-
hyper: A fast and correct HTTP/1.1 and HTTP/2 implementation for Rust. -
tonic: A gRPC over HTTP/2 implementation focused on high performance, interoperability, and flexibility. -
warp: A super-easy, composable, web server framework for warp speeds. -
tower: A library of modular and reusable components for building robust networking clients and servers. -
tracing(formerlytokio-trace): A framework for application-level tracing and async-aware diagnostics. -
rdbc: A Rust database connectivity library for MySQL, Postgres and SQLite. -
mio: A low-level, cross-platform abstraction over OS I/O APIs that powerstokio. -
bytes: Utilities for working with bytes, including efficient byte buffers. -
loom: A testing tool for concurrent Rust code
Supported Rust Versions
Tokio will keep a rolling MSRV (minimum supported rust version) policy of at least 6 months. When increasing the MSRV, the new Rust version must have been released at least six months ago. The current MSRV is 1.49.0.
Release schedule
Tokio doesn't follow a fixed release schedule, but we typically make one to two new minor releases each month. We make patch releases for bugfixes as necessary.
Bug patching policy
For the purposes of making patch releases with bugfixes, we have designated certain minor releases as LTS (long term support) releases. Whenever a bug warrants a patch release with a fix for the bug, it will be backported and released as a new patch release for each LTS minor version. Our current LTS releases are:
1.8.x- LTS release until February 2022.1.14.x- LTS release until June 2022.
Each LTS release will continue to receive backported fixes for at least half a year. If you wish to use a fixed minor release in your project, we recommend that you use an LTS release.
To use a fixed minor version, you can specify the version with a tilde. For
example, to specify that you wish to use the newest 1.8.x patch release, you
can use the following dependency specification:
tokio = { version = "~1.8", features = [...] }
License
This project is licensed under the MIT license.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Tokio by you, shall be licensed as MIT, without any additional terms or conditions.