rust 异步,-Rust异步取消策略:深入理解与实践指南 - created_at: Instant,
引言:异步编程中的取消挑战
在现代异步应用开发中,取消操作是一个至关重要但常常被忽视的方面。无论是当请求超时、用户取消操作或服务需要优雅关闭时,我们需要一种
效地取消正在执行的异步任务,释放释放资源,并避免潜在的内存泄漏或不一致状态。Rust作为一门注重安全和性能的系统级编程语言,提供了强大而灵活的异步取消机制。本文将深入探讨Rust中异步取消的原理、策略和最佳实践,帮助开发者构建健壮、高效的异步应用。
一、Rust异步取消的基础
1.1 取消的概念与重要性
异步取消是指在异步任务完成之前终止其执行的过程。在以下场景中尤为重要:
请求超时:当异步操作超过预设时间时用户取消:当用户主动取消正在进行的操作时服务关闭:当应用需要优雅地停止时错误处理:当一个操作失败导致后续操作不再需要时
use std::time::Duration;
use tokio::time;
async fn fetch_data_with_timeout(url: &str) ->Result> {
// 设置5秒超时
time::timeout(Duration::from_secs(5), async {
// 模拟网络请求
time::sleep(Duration::from_secs(3)).await;
Ok("Data from server".to_string())
}).await??
}
1.2 Rust的取消模型
Rust采用协作式取消模型,这意味着:
任务不会被强制终止任务需要显式检查取消状态取消通过CancellationToken或Select等机制触发
use tokio::sync::CancellationToken;
use tokio::time;
async fn long_running_task(ct: CancellationToken) ->Result<(), Box> {
for i in 0..10 {
// 检查是否收到取消信号
if ct.is_cancelled() {
return Err("Task was cancelled".into());
}
println!("Working... {}/10", i + 1);
time::sleep(Duration::from_secs(1)).await;
}
Ok(())
}
#[tokio::main]
async fn main() { 拼多多帮助力入口
let ct = CancellationToken::new();
let ct_clone = ct.clone();
// 启动一个任务来触发取消
tokio::spawn(async move {
time::sleep(Duration::from_secs(3)).await;
println!("Cancelling task...");
ct_clone.cancel();
});
// 运行长时间任务
match long_running_task(ct).await {
Ok(_) => println!("Task completed successfully"),
Err(e) => println!("Task failed: {}", e),
}
}
1.3 取消的传播机制
在Rust中,取消可以通过以下方式传播:
显式传递:通过函数参数传递取消令牌select!宏:当一个分支完成时取消其他分支join!宏:当一个任务失败时取消其他任务
use tokio::select;
use tokio::time;
async fn operation_a() ->String {
time::sleep(Duration::from_secs(2)).await;
"Result from A".to_string()
}
async fn operation_b() ->String {
time::sleep(Duration::from_secs(1)).await;
"Result from B".to_string()
}
async fn race_operations() ->String {
select! {
res_a = operation_a() => res_a,
res_b = operation_b() => res_b,
}
}
#[tokio::main]
async fn main() {
let result = race_operations().await;
println!("Fastest result: {}", result);
}
二、深入理解Rust的取消机制
2.1 任务取消的内部原理
Rust的异步运行时(如Tokio)通过以下机制实现任务取消:
任务状态标记:运行时维护每个任务的取消状态唤醒机制:当任务被取消时,运行时会唤醒任务协作检查:任务在适当的点检查取消状态
// 简化的任务结构
struct Task {
state: TaskState,
waker: Option,
// 其他字段...
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TaskState {
Running,
Pending,
Cancelled,
Completed,
}
impl Task {
fn cancel(&mut self) {
self.state = TaskState::Cancelled;
// 如果任务处于挂起状态,唤醒它
if let Some(waker) = &self.waker {
waker.wake_by_ref();
}
}
fn is_cancelled(&self) ->bool {
self.state == TaskState::Cancelled
}
}
2.2 CancellationToken的实现机制
CancellationToken是Tokio提供的一个强大工具,用于传播取消信号:
use tokio::sync::CancellationToken;
use tokio::time;
async fn nested_operations(ct: CancellationToken) ->Result<(), Box> {
// 创建子取消令牌
let child_ct = ct.child_token();
// 启动子任务
let child_task = tokio::spawn(async move {
for i in 0..5 {
if child_ct.is_cancelled() {
println!("Child task cancelled");
return;
}
println!("Child working... {}/5", i + 1);
time::sleep(Duration::from_secs(1)).await;
}
println!("Child task completed");
});
// 模拟主任务工作
time::sleep(Duration::from_secs(2)).await;
println!("Cancelling child task...");
// 取消子任务
child_ct.cancel();
// 等待子任务完成
child_task.await?;
Ok(())
}
#[tokio::main]
async fn main() ->Result<(), Box> {
let ct = CancellationToken::new();
nested_operations(ct).await?;
Ok(())
}
2.3 取消安全(Cancellation Safety)
取消安全是指异步操作在被取消时不会导致资源泄漏或不一致状态。Rust提供了CancellationSafety trait来标记类型的取消安全性:
use tokio::io::{self, AsyncRead, AsyncWrite};
use tokio::net::TcpStream;
use tokio::sync::CancellationToken;
// 取消安全的操作
async fn safe_operation(mut stream: TcpStream, ct: CancellationToken) ->io::Result<()> {
// 使用with_timeout确保操作可以被取消
tokio::time::timeout_at(
tokio::time::Instant::now() + tokio::time::Duration::from_secs(10),
async move {
let mut buffer = [0; 1024];
loop {
// 检查取消令牌
if ct.is_cancelled() {
return Err(io::ErrorKind::Interrupted.into());
}
// 读取数据(取消安全的操作)
let n = stream.read(&mut buffer).await?;
if n == 0 {
break;
}
// 处理数据
println!("Received {} bytes", n);
}
Ok(())
}
).await??;
Ok(())
}
三、实用的异步取消策略
3.1 超时取消策略
超时是最常见的取消场景之一。Rust提供了多种实现超时的方式:
use std::time::Duration;
use tokio::time;
use tokio::sync::CancellationToken;
// 方式1:使用time::timeout
async fn fetch_with_timeout() ->Result> {
time::timeout(Duration::from_secs(5), async {
// 模拟网络请求
time::sleep(Duration::from_secs(3)).await;
Ok("Data received".to_string())
}).await??
}
// 方式2:使用CancellationToken和time::sleep
async fn fetch_with_ct() ->Result> {
let ct = CancellationToken::new();
let ct_clone = ct.clone();
// 启动超时任务
tokio::spawn(async move {
time::sleep(Duration::from_secs(5)).await;
ct_clone.cancel();
});
// 模拟网络请求,定期检查取消状态
let mut delay = time::sleep(Duration::from_millis(100));
loop {
if ct.is_cancelled() {
return Err("Request timed out".into());
}
// 检查是否完成(模拟)
if check_if_completed().await {
return Ok("Data received".to_string());
}
// 等待一段时间后再次检查
delay.await;
delay = time::sleep(Duration::from_millis(100));
}
}
// 模拟检查操作是否完成
async fn check_if_completed() ->bool {
// 实际应用中这里会检查操作状态
static mut COUNT: u32 = 0;
unsafe {
COUNT += 1;
COUNT >= 30 // 3秒后返回true
}
}
3.2 层级取消策略
在复杂的应用中,我们需要实现层级化的取消策略:
use tokio::sync::CancellationToken;
use tokio::time;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
// 工作单元
async fn worker(id: usize, ct: CancellationToken) {
let mut attempt = 0;
loop {
if ct.is_cancelled() {
println!("Worker {}: cancelled", id);
return;
}
attempt += 1;
println!("Worker {}: working on attempt {}", id, attempt);
// 模拟工作
time::sleep(Duration::from_secs(1)).await;
// 模拟随机完成
if rand::random::() < 0.2 {
println!("Worker {}: completed after {} attempts", id, attempt);
return;
}
}
}
// 工作管理器
async fn work_manager(num_workers: usize) {
let root_ct = CancellationToken::new();
// 创建工作取消令牌(可以独立取消)
let work_ct = root_ct.child_token();
// 跟踪完成的工作数
let completed = Arc::new(AtomicUsize::new(0));
let total_workers = num_workers;
// 启动工作线程
let mut handles = Vec::new();
for i in 0..num_workers {
let ct = work_ct.clone();
let completed = completed.clone();
handles.push(tokio::spawn(async move {
worker(i, ct).await;
completed.fetch_add(1, Ordering::SeqCst);
}));
}
// 等待直到一半的工作完成,然后取消剩余工作
loop {
let count = completed.load(Ordering::SeqCst);
if count >= total_workers / 2 {
println!("Manager: {} workers completed, cancelling remaining", count);
work_ct.cancel();
break;
}
time::sleep(Duration::from_millis(100)).await;
}
// 等待所有工作线程完成
for handle in handles {
let _ = handle.await;
}
println!("Manager: all workers finished");
}
#[tokio::main]
async fn main() {
work_manager(10).await;
}
3.3 选择性取消策略
有时我们需要根据条件选择性地取消任务:
use tokio::sync::{CancellationToken, mpsc};
use tokio::time;
use std::collections::HashMap;
// 任务状态
#[derive(Debug, Clone, PartialEq)]
enum TaskStatus {
Running,
Completed,
Cancelled,
Failed(String),
}
// 任务管理器
struct TaskManager {
tasks: HashMap)>,
next_id: u64,
}
impl TaskManager {
fn new() ->Self {
TaskManager {
tasks: HashMap::new(),
next_id: 0,
}
}
// 启动新任务
fn spawn_task(&mut self, f: F) ->u64
where
F: std::future::Future> + Send + 'static,
{
let task_id = self.next_id;
self.next_id += 1;
let ct = CancellationToken::new();
let ct_clone = ct.clone();
let (status_tx, mut status_rx) = mpsc::channel(1);
// 启动任务
tokio::spawn(async move {
status_tx.send(TaskStatus::Running).await.unwrap();
let result = tokio::select! {
res = f => res,
_ = ct_clone.cancelled() => Err("Task cancelled".to_string()),
};
match result {
Ok(_) => status_tx.send(TaskStatus::Completed).await.unwrap(),
Err(e) => status_tx.send(TaskStatus::Failed(e)).await.unwrap(),
}
});
// 监控任务状态
tokio::spawn(async move {
while let Some(status) = status_rx.recv().await {
println!("Task {} status: {:?}", task_id, status);
if status == TaskStatus::Completed || status == TaskStatus::Cancelled ||
matches!(status, TaskStatus::Failed(_)) {
break;
}
}
});
self.tasks.insert(task_id, (ct, status_tx));
task_id
}
// 取消任务
fn cancel_task(&mut self, task_id: u64) ->bool {
if let Some((ct, _)) = self.tasks.remove(&task_id) {
ct.cancel();
true
} else {
false
}
}
// 取消所有任务
fn cancel_all(&mut self) {
for (_, (ct, _)) in self.tasks.drain() {
ct.cancel();
}
}
// 根据条件取消任务
fn cancel_by_condition(&mut self, condition: F)
where
F: Fn(u64) ->bool,
{
let to_cancel: Vec= self.tasks.keys()
.filter(|&&id| condition(id))
.cloned()
.collect();
for task_id in to_cancel {
self.cancel_task(task_id);
}
}
}
// 模拟长时间运行的任务
async fn simulated_work(duration: Duration, fail_probability: f32) ->Result<(), String>{
let end_time = tokio::time::Instant::now() + duration;
while tokio::time::Instant::now() < end_time {
// 模拟工作
time::sleep(Duration::from_millis(100)).await;
// 模拟随机失败
if rand::random::() < fail_probability {
return Err("Random failure".to_string());
}
}
Ok(())
}
#[tokio::main]
async fn main() {
let mut manager = TaskManager::new();
// 启动多个任务
let task1 = manager.spawn_task(simulated_work(Duration::from_secs(5), 0.05));
let task2 = manager.spawn_task(simulated_work(Duration::from_secs(10), 0.1));
let task3 = manager.spawn_task(simulated_work(Duration::from_secs(3), 0.0));
let task4 = manager.spawn_task(simulated_work(Duration::from_secs(7), 0.2));
// 运行一段时间
time::sleep(Duration::from_secs(2)).await;
// 取消任务2
println!("Cancelling task 2");
manager.cancel_task(task2);
// 运行一段时间
time::sleep(Duration::from_secs(2)).await;
// 取消ID大于2的任务
println!("Cancelling tasks with ID > 2");
manager.cancel_by_condition(|id| id > 2);
// 等待所有任务完成
time::sleep(Duration::from_secs(3)).await;
println!("Main: all done");
}
四、深度实践:构建可取消的异步服务
让我们通过一个完整的示例来展示如何在实际项目中实现健壮的异步取消策略:
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio::sync::{CancellationToken, mpsc, RwLock};
use tokio::time;
use hyper::{Body, Request, Response, Server, StatusCode};
use hyper::service::{make_service_fn, service_fn};
use serde::{Deserialize, Serialize};
// 任务状态
#[derive(Debug, Clone, Serialize, Deserialize)]
enum TaskStatus {
Pending,
Running,
Completed(String),
Failed(String),
Cancelled,
}
// 任务元数据
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TaskMetadata {
id: String,
status: TaskStatus,
created_at: Instant,
started_at: Option,
completed_at: Option,
progress: u8, // 0-100
}
// 任务管理器
struct TaskManager {
tasks: Arc>>,cancellation_tokens: Arc>>,shutdown_token: CancellationToken,
}
impl TaskManager {
fn new(shutdown_token: CancellationToken) ->Self {
TaskManager {
tasks: Arc::new(RwLock::new(HashMap::new())),
cancellation_tokens: Arc::new(Mutex::new(HashMap::new())),
shutdown_token,
}
}
// 创建新任务
async fn create_task(&self, task_type: String, params: serde_json::Value) ->String {
let task_id = format!("task_{}", uuid::Uuid::new_v4());
let now = Instant::now();
// 创建任务元数据
let task_metadata = TaskMetadata {
id: task_id.clone(),
status: TaskStatus::Pending,
created_at: now,
started_at: None,
completed_at: None,
progress: 0,
};
// 创建取消令牌
let ct = CancellationToken::new();
let ct_clone = ct.clone();
let shutdown_clone = self.shutdown_token.clone();
// 保存任务信息
{
let mut tasks = self.tasks.write().await;
tasks.insert(task_id.clone(), task_metadata);
let mut tokens = self.cancellation_tokens.lock().unwrap();
tokens.insert(task_id.clone(), ct);
}
// 启动任务处理
let tasks_clone = self.tasks.clone();
tokio::spawn(async move {
// 更新任务状态为运行中
{
let mut tasks = tasks_clone.write().await;
if let Some(task) = tasks.get_mut(&task_id) {
task.status = TaskStatus::Running;
task.started_at = Some(Instant::now());
}
}
// 执行任务
let result = tokio::select! {
res = execute_task(task_type, params, tasks_clone.clone(), task_id.clone()) => res,
_ = ct_clone.cancelled() => Err("Task cancelled by user".to_string()),
_ = shutdown_clone.cancelled() => Err("Task cancelled due to server shutdown".to_string()),
};
// 更新任务状态
{
let mut tasks = tasks_clone.write().await;
if let Some(task) = tasks.get_mut(&task_id) {
task.completed_at = Some(Instant::now());
match result {
Ok(output) => {
task.status = TaskStatus::Completed(output);
task.progress = 100;
}
Err(error) => {
task.status = TaskStatus::Failed(error);
}
}
}
}
// 清理取消令牌
{
let mut tokens = self.cancellation_tokens.lock().unwrap();
tokens.remove(&task_id);
}
});
task_id
}
// 获取任务状态
async fn get_task_status(&self, task_id: &str) ->Option{
let tasks = self.tasks.read().await;
tasks.get(task_id).cloned()
}
// 取消任务
async fn cancel_task(&self, task_id: &str) ->bool {
let mut tokens = self.cancellation_tokens.lock().unwrap();
if let Some(ct) = tokens.get(task_id) {
ct.cancel();
// 更新任务状态
let mut tasks = self.tasks.write().await;
if let Some(task) = tasks.get_mut(task_id) {
task.status = TaskStatus::Cancelled;
task.completed_at = Some(Instant::now());
}
true
} else {
false
}
}
// 获取所有任务
async fn list_tasks(&self) ->Vec{
let tasks = self.tasks.read().await;
tasks.values().cloned().collect()
}
}
// 执行具体任务
async fn execute_task(
task_type: String,
params: serde_json::Value,
tasks: Arc>>,task_id: String,
) ->Result{
match task_type.as_str() {
"data_processing" => {
// 模拟数据处理任务
let iterations = params.get("iterations").and_then(|v| v.as_u64()).unwrap_or(10);
let delay = params.get("delay").and_then(|v| v.as_u64()).unwrap_or(100);
for i in 0..=iterations {
// 更新进度
{
let progress = ((i as f64 / iterations as f64) * 100.0) as u8;
let mut tasks = tasks.write().await;
if let Some(task) = tasks.get_mut(&task_id) {
task.progress = progress;
}
}
if i < iterations {
// 模拟工作
time::sleep(Duration::from_millis(delay)).await;
}
}
Ok(format!("Data processing completed in {} iterations", iterations))
}
"file_download" => {
// 模拟文件下载任务
let size_mb = params.get("size_mb").and_then(|v| v.as_f64()).unwrap_or(10.0);
let speed_mbps = params.get("speed_mbps").and_then(|v| v.as_f64()).unwrap_or(10.0);
// 计算总字节数和预计时间
let total_bytes = (size_mb * 1024.0 * 1024.0) as u64;
let bytes_per_second = (speed_mbps * 125000.0) as u64; // 1 Mbps = 125,000 bytes/sec
let total_time = Duration::from_secs_f64(total_bytes as f64 / bytes_per_second as f64);
let start_time = Instant::now();
let mut downloaded_bytes = 0;
while downloaded_bytes < total_bytes {
// 模拟下载一块数据
let chunk_size = std::cmp::min(1024 * 1024, total_bytes - downloaded_bytes);
downloaded_bytes += chunk_size;
// 更新进度
{
let progress = ((downloaded_bytes as f64 / total_bytes as f64) * 100.0) as u8;
let mut tasks = tasks.write().await;
if let Some(task) = tasks.get_mut(&task_id) {
task.progress = progress;
}
}
// 计算应该等待的时间
let elapsed = start_time.elapsed();
let expected_bytes = (elapsed.as_secs_f64() * bytes_per_second as f64) as u64;
if downloaded_bytes > expected_bytes {
// 我们比预期快,需要等待
let excess = downloaded_bytes - expected_bytes;
let wait_time = Duration::from_secs_f64(excess as f64 / bytes_per_second as f64);
time::sleep(wait_time).await;
} else {
// 正常进度,短暂等待
time::sleep(Duration::from_millis(10)).await;
}
}
Ok(format!("Downloaded {} MB at {} Mbps", size_mb, speed_mbps))
}
_ => Err(format!("Unknown task type: {}", task_type)),
}
}
// HTTP请求处理
async fn handle_request(
req: Request,
task_manager: Arc,
) ->Result, hyper::Error>{let path = req.uri().path();
let method = req.method();
match (method, path) {
(&hyper::Method::POST, "/tasks") => {
// 创建新任务
let body = hyper::body::to_bytes(req.into_body()).await.unwrap();
let task_request: serde_json::Value = match serde_json::from_slice(&body) {
Ok(req) => req,
Err(e) => {
return Ok(Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(Body::from(format!("Invalid JSON: {}", e)))
.unwrap());
}
};
let task_type = task_request.get("type")
.and_then(|v| v.as_str())
.unwrap_or("unknown")
.to_string();
let params = task_request.get("params").cloned().unwrap_or(serde_json::Value::Null);
let task_id = task_manager.create_task(task_type, params).await;
Ok(Response::new(Body::from(format!(
"{{\"task_id\": \"{}\"}}", task_id
))))
}
(&hyper::Method::GET, "/tasks") => {
// 获取所有任务
let tasks = task_manager.list_tasks().await;
let tasks_json = serde_json::to_string(&tasks).unwrap();
Ok(Response::new(Body::from(tasks_json)))
}
(&hyper::Method::GET, path) if path.starts_with("/tasks/") => {
// 获取特定任务状态
let task_id = path.split('/').last().unwrap_or("");
match task_manager.get_task_status(task_id).await {
Some(status) => {
let status_json = serde_json::to_string(&status).unwrap();
Ok(Response::new(Body::from(status_json)))
}
None => {
Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::from("Task not found"))
.unwrap())
}
}
}
(&hyper::Method::DELETE, path) if path.starts_with("/tasks/") => {
// 取消任务
let task_id = path.split('/').last().unwrap_or("");
if task_manager.cancel_task(task_id).await {
Ok(Response::new(Body::from(format!(
"{{\"status\": \"cancelled\", \"task_id\": \"{}\"}}", task_id
))))
} else {
Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::from("Task not found or already completed"))
.unwrap())
}
}
_ => {
Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::from("Not found"))
.unwrap())
}
}
}
#[tokio::main]
async fn main() {
// 创建关闭令牌
let shutdown_token = CancellationToken::new();
let shutdown_clone = shutdown_token.clone();
// 设置信号处理
tokio::spawn(async move {
// 监听SIGINT和SIGTERM信号
let mut sigint = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt()).unwrap();
let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).unwrap();
tokio::select! {
_ = sigint.recv() => println!("Received SIGINT, shutting down"),
_ = sigterm.recv() => println!("Received SIGTERM, shutting down"),
}
// 触发关闭
shutdown_clone.cancel();
});
// 创建任务管理器
let task_manager = Arc::new(TaskManager::new(shutdown_token.clone()));
// 绑定地址
let addr = ([127, 0, 0, 1], 3000).into();
// 创建服务
let make_svc = make_service_fn(move |_conn| {
let task_manager = task_manager.clone();
async move {
Ok::<_, hyper::Error>(service_fn(move |req| {
handle_request(req, task_manager.clone())
}))
}
});
// 启动服务器
let server = Server::bind(&addr).serve(make_svc);
println!("Server running on http://{}", addr);
println!("API endpoints:");
println!(" POST /tasks - Create new task");
println!(" GET /tasks - List all tasks");
println!(" GET /tasks/{id} - Get task status");
println!(" DELETE /tasks/{id} - Cancel task");
// 运行服务器直到关闭信号
let graceful = server.with_graceful_shutdown(async move {
shutdown_token.cancelled().await;
println!("Server is shutting down gracefully...");
});
if let Err(e) = graceful.await {
eprintln!("Server error: {}", e);
}
println!("Server stopped");
}
代码分析与最佳实践
层级取消设计:
使用CancellationToken实现层级化的取消机制根取消令牌用于服务器关闭每个任务有自己的取消令牌,支持单独取消
任务状态管理:
详细的任务状态跟踪(Pending、Running、Completed、Failed、Cancelled)进度监控(0-100%)时间戳记录(创建时间、开始时间、完成时间)
资源清理:
任务完成后清理取消令牌使用RwLock和Mutex确保线程安全优雅的服务器关闭流程
API设计:
RESTful API接口JSON请求和响应格式完整的错误处理
五、取消策略的性能考量
5.1 取消检查的开销
频繁的取消检查可能会影响性能,需要平衡响应性和性能:
use tokio::sync::CancellationToken;
use tokio::time;
// 不推荐:过于频繁的取消检查
async fn inefficient_task(ct: CancellationToken) {
for i in 0..1_000_000 {
// 每次迭代都检查,开销较大
if ct.is_cancelled() {
return;
}
// 简单的计算任务
let _ = i * i;
}
}
// 推荐:批量处理并定期检查
async fn efficient_task(ct: CancellationToken) {
const BATCH_SIZE: usize = 10_000;
for batch in 0..100 {
// 每处理一批检查一次
if ct.is_cancelled() {
return;
}
// 处理一批数据
for i in 0..BATCH_SIZE {
let _ = (batch * BATCH_SIZE + i) * (batch * BATCH_SIZE + i);
}
}
}
// 推荐:使用select!宏进行非阻塞等待
async fn non_blocking_task(ct: CancellationToken) ->Result<(), String>{
tokio::select! {
_ = ct.cancelled() => Err("Task cancelled".to_string()),
result = async {
// 长时间运行的操作
let mut result = 0;
for i in 0..1_000_000 {
result += i;
}
Ok(result)
} => result.map(|r| println!("Result: {}", r)),
}
}
5.2 取消安全的数据结构
设计支持安全取消的数据结构:
use tokio::sync::CancellationToken;
use tokio::time;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
// 取消安全的工作队列
struct CancellationSafeQueue{
queue: Arc>>,cancelled: Arc,
}
implCancellationSafeQueue{
fn new() ->Self {
CancellationSafeQueue {
queue: Arc::new(tokio::sync::Mutex::new(Vec::new())),
cancelled: Arc::new(AtomicBool::new(false)),
}
}
async fn push(&self, item: T) ->Result<(), ()> {
if self.cancelled.load(Ordering::SeqCst) {
return Err(());
}
let mut queue = self.queue.lock().await;
if self.cancelled.load(Ordering::SeqCst) {
return Err(());
}
queue.push(item);
Ok(())
}
async fn pop(&self) ->Option{
if self.cancelled.load(Ordering::SeqCst) {
return None;
}
let mut queue = self.queue.lock().await;
if self.cancelled.load(Ordering::SeqCst) {
return None;
}
queue.pop()
}
fn cancel(&self) {
self.cancelled.store(true, Ordering::SeqCst);
}
fn is_cancelled(&self) ->bool {
self.cancelled.load(Ordering::SeqCst)
}
}
// 使用示例
async fn process_queue(
queue: CancellationSafeQueue,
processor: F,
ct: CancellationToken,
) where
F: Fn(T) ->Result<(), String>+ Send + Sync + 'static,
T: Send + 'static,
{
loop {
tokio::select! {
_ = ct.cancelled() => {
queue.cancel();
println!("Queue processing cancelled");
return;
}
item = queue.pop() => {
match item {
Some(item) => {
if let Err(e) = processor(item) {
println!("Error processing item: {}", e);
}
}
None => {
// 队列为空,等待一段时间
time::sleep(Duration::from_millis(100)).await;
}
}
}
}
}
}
5.3 取消与资源管理
确保在取消时正确释放资源:
use tokio::sync::CancellationToken;
use tokio::time;
use std::fs::File;
use std::io::{self, Write};
use std::path::Path;
// 带有取消安全的文件写入器
struct CancellableFileWriter {
file: Option,
buffer: Vec,
ct: CancellationToken,
}
impl CancellableFileWriter {
async fn new(path: &Path, ct: CancellationToken) ->io::Result{
// 检查是否已取消
if ct.is_cancelled() {
return Err(io::ErrorKind::Interrupted.into());
}
// 同步操作,需要阻塞运行时
let file = tokio::task::spawn_blocking(move || File::create(path))
.await
.map_err(|_| io::ErrorKind::Other)?;
Ok(CancellableFileWriter {
file: Some(file?),
buffer: Vec::new(),
ct,
})
}
async fn write(&mut self, data: &[u8]) ->io::Result<()> {
// 检查是否已取消
if self.ct.is_cancelled() {
return Err(io::ErrorKind::Interrupted.into());
}
// 将数据添加到缓冲区
self.buffer.extend_from_slice(data);
// 如果缓冲区足够大,尝试写入
if self.buffer.len() >= 4096 {
self.flush().await?;
}
Ok(())
}
async fn flush(&mut self) ->io::Result<()> {
// 检查是否已取消
if self.ct.is_cancelled() {
return Err(io::ErrorKind::Interrupted.into());
}
if let Some(file) = &mut self.file {
let data = std::mem::take(&mut self.buffer);
// 同步操作,需要阻塞运行时
tokio::task::spawn_blocking(move || file.write_all(&data))
.await
.map_err(|_| io::ErrorKind::Other)??;
}
Ok(())
}
async fn close(mut self) ->io::Result<()> {
// 确保所有数据都已写入
if !self.buffer.is_empty() {
self.flush().await?;
}
// 关闭文件
if let Some(mut file) = self.file.take() {
tokio::task::spawn_blocking(move || file.sync_all())
.await
.map_err(|_| io::ErrorKind::Other)??;
}
Ok(())
}
}
// 使用示例
async fn write_large_data(
path: &Path,
data_size_mb: usize,
ct: CancellationToken,
) ->io::Result<()> {
let mut writer = CancellableFileWriter::new(path, ct.clone()).await?;
let chunk_size = 1024 * 1024; // 1MB
let total_chunks = data_size_mb;
let data = vec![0u8; chunk_size];
for i in 0..total_chunks {
// 检查取消
if ct.is_cancelled() {
// 尝试优雅关闭
let _ = writer.close().await;
return Err(io::ErrorKind::Interrupted.into());
}
// 写入数据
writer.write(&data).await?;
// 打印进度
println!("Wrote chunk {}/{}", i + 1, total_chunks);
// 模拟工作
time::sleep(Duration::from_millis(100)).await;
}
// 完成写入
writer.close().await
}
六、取消策略的最佳实践
6.1 设计可取消的异步函数
use tokio::sync::CancellationToken;
use tokio::time;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
// 可取消的异步函数 trait
trait CancellableFuture: Future {
fn with_cancellation(self, ct: CancellationToken) ->Cancellable
where
Self: Sized,
{
Cancellable {
future: self,
ct,
}
}
}
implCancellableFuture for F {}
// 可取消的Future包装器
struct Cancellable{
future: F,
ct: CancellationToken,
}
implFuture for Cancellable{
type Output = Result;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) ->Poll{
// 首先检查是否已取消
if self.ct.is_cancelled() {
return Poll::Ready(Err(()));
}
// 注册唤醒
let waker = cx.waker().clone();
let ct = self.ct.clone();
tokio::spawn(async move {
ct.cancelled().await;
waker.wake();
});
// 轮询内部future
match Pin::new(&mut self.future).poll(cx) {
Poll::Ready(output) => Poll::Ready(Ok(output)),
Poll::Pending => Poll::Pending,
}
}
}
// 使用示例
async fn long_operation() ->String {
time::sleep(Duration::from_secs(5)).await;
"Operation completed".to_string()
}
#[tokio::main]
async fn main() {
let ct = CancellationToken::new();
let ct_clone = ct.clone();
// 启动取消任务
tokio::spawn(async move {
time::sleep(Duration::from_secs(2)).await;
ct_clone.cancel();
});
// 使用可取消的future
match long_operation().with_cancellation(ct).await {
Ok(result) => println!("Result: {}", result),
Err(_) => println!("Operation was cancelled"),
}
}
6.2 错误处理与取消
正确处理取消导致的错误:
use tokio::sync::CancellationToken;
use tokio::time;
use thiserror::Error;
// 自定义错误类型
#[derive(Error, Debug)]
enum AppError {
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("Task cancelled")]
Cancelled,
#[error("Timeout")]
Timeout,
#[error("Other error: {0}")]
Other(String),
}
// 取消令牌扩展
trait CancellationTokenExt {
async fn cancelled_as_error(self) ->AppError;
}
impl CancellationTokenExt for CancellationToken {
async fn cancelled_as_error(self) ->AppError {
self.cancelled().await;
AppError::Cancelled
}
}
// 带超时和取消的操作
async fn operation_with_timeout_and_cancellation(
timeout: Duration,
ct: CancellationToken,
) ->Result<(), AppError>{
tokio::select! {
_ = ct.cancelled_as_error() => Err(AppError::Cancelled),
_ = time::sleep(timeout) => Err(AppError::Timeout),
result = async {
// 模拟操作
time::sleep(Duration::from_secs(3)).await;
Ok(())
} => result,
}
}
// 重试逻辑
async fn operation_with_retry(
max_retries: usize,
initial_delay: Duration,
ct: CancellationToken,
) ->Result<(), AppError>{
let mut retries = 0;
loop {
match operation_with_timeout_and_cancellation(Duration::from_secs(5), ct.clone()).await {
Ok(result) => return Ok(result),
Err(AppError::Cancelled) => {
// 取消错误不重试
return Err(AppError::Cancelled);
}
Err(error) => {
retries += 1;
if retries >= max_retries {
return Err(AppError::Other(format!(
"Max retries exceeded. Last error: {}", error
)));
}
println!("Operation failed ({}), retrying in {:?}...", error, initial_delay);
// 等待重试
tokio::select! {
_ = ct.cancelled_as_error() => return Err(AppError::Cancelled),
_ = time::sleep(initial_delay) => {},
}
}
}
}
}
#[tokio::main]
async fn main() {
let ct = CancellationToken::new();
let ct_clone = ct.clone();
// 启动取消任务
tokio::spawn(async move {
time::sleep(Duration::from_secs(10)).await;
println!("Cancelling operation...");
ct_clone.cancel();
});
match operation_with_retry(3, Duration::from_secs(2), ct).await {
Ok(_) => println!("Operation completed successfully"),
Err(e) => println!("Operation failed: {}", e),
}
}
6.3 测试取消行为
编写测试来验证取消行为:
use tokio::sync::CancellationToken;
use tokio::time;
use tokio::test;
// 被测试的函数
async fn cancellable_function(ct: CancellationToken) ->Result<(), String>{
for i in 0..10 {
if ct.is_cancelled() {
return Err("Task cancelled".to_string());
}
time::sleep(Duration::from_millis(100)).await;
}
Ok(())
}
// 测试正常完成
#[test]
async fn test_function_completes_normally() {
let ct = CancellationToken::new();
let result = cancellable_function(ct).await;
assert!(result.is_ok());
}
// 测试取消功能
#[test]
async fn test_function_cancels() {
let ct = CancellationToken::new();
let ct_clone = ct.clone();
// 启动任务
let task = tokio::spawn(async move {
cancellable_function(ct).await
});
// 等待一段时间后取消
time::sleep(Duration::from_millis(500)).await;
ct_clone.cancel();
// 等待任务完成
let result = task.await.unwrap();
// 验证任务被取消
assert!(result.is_err());
assert_eq!(result.err().unwrap(), "Task cancelled");
}
// 测试立即取消
#[test]
async fn test_immediate_cancellation() {
let ct = CancellationToken::new();
ct.cancel(); // 立即取消
let result = cancellable_function(ct).await;
assert!(result.is_err());
assert_eq!(result.err().unwrap(), "Task cancelled");
}
// 测试超时取消
#[test]
async fn test_timeout_cancellation() {
let ct = CancellationToken::new();
let ct_clone = ct.clone();
// 设置超时取消
tokio::spawn(async move {
time::sleep(Duration::from_millis(300)).await;
ct_clone.cancel();
});
let result = cancellable_function(ct).await;
assert!(result.is_err());
assert_eq!(result.err().unwrap(), "Task cancelled");
}
七、总结与展望
7.1 异步取消策略总结
Rust提供了多种强大的异步取消策略:
超时取消:使用tokio::time::timeout实现操作超时显式取消:使用CancellationToken手动触发取消选择性取消:使用select!宏实现多个任务的竞争层级取消:使用CancellationToken::child_token实现取消的层级传播组合取消:结合多种策略实现复杂的取消逻辑
7.2 最佳实践清单
始终支持取消:在长时间运行的异步函数中添加取消检查合理的检查频率:平衡响应性和性能正确处理资源:确保取消时释放所有资源清晰的错误处理:区分取消错误和其他错误测试取消行为:编写测试验证取消功能文档化取消策略:明确说明函数的取消行为
7.3 未来发展方向
Rust的异步取消机制仍在不断发展:
标准化取消API:未来可能会有更统一的取消API编译器支持:可能会有更好的编译器支持来优化取消检查更多取消安全保证:增强类型系统对取消安全的支持
结论
异步取消是构建健壮、高效异步应用的关键组成部分。Rust提供了灵活而强大的取消机制,使开发者能够实现精细的取消策略。通过深入理解Rust的取消模型和实践本文介绍的策略,开发者可以构建出能够优雅处理取消的异步应用,提升系统的可靠性和用户体验。
掌握异步取消不仅是技术能力的体现,更是设计高质量异步系统的必备技能。随着Rust异步生态的不断成熟,我们有理由相信,Rust将在异步编程领域继续发挥重要作用,为构建高性能、可靠的现代应用提供强大支持。