第 8 章:并发与异步

第 8 章:并发与异步

8.1 线程基础

Rust 提供了 std::thread 模块来创建线程。

use std::thread;

let handle = thread::spawn(|| {
    println!("Hello from a thread");
});
handle.join().unwrap();

8.2 共享状态与消息传递

Mutex

use std::sync::{Arc, Mutex};

let counter = Arc::new(Mutex::new(0));
  • Mutex 用于保护共享可变数据
  • Arc 用于跨线程共享所有权

mpsc

use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
  • 发送端 tx 可发送消息
  • 接收端 rx 接收消息

8.3 async/await 基础

Rust 的异步模型基于 Future

async fn hello() {
    println!("Hello async");
}

#[tokio::main]
async fn main() {
    hello().await;
}
  • async fn 定义异步函数
  • .await 等待 Future 完成

8.4 常用异步运行时

  • tokio
  • async-std

示例:使用 tokio 发送 HTTP 请求或处理并发任务。

8.5 练习

  • 构建一个计数器线程,使用 Arc<Mutex<_>> 进行共享
  • 实现一个生产者/消费者模型
  • 使用 tokio 写一个简单异步网络客户端
posted on 2026-05-09 22:02  小樊童鞋  阅读(9)  评论(0)    收藏  举报