显示页面讨论过去修订反向链接回到顶部 本页面只读。您可以查看源文件,但不能更改它。如果您觉得这是系统错误,请联系管理员。 # 32. 并发基础 ## 学习目标 - 理解 Rust 如何使用线程实现并发。 - 掌握 `thread::spawn` 和 `join` 的用法。 - 使用通道(channel)在线程间传递消息。 - 使用 `Arc<Mutex<T>>` 实现共享状态并发。 - 理解 `Send` 和 `Sync` trait 的安全保证。 ## 32.1 创建线程 使用 `std::thread::spawn` 创建新线程: ```rust use std::thread; use std::time::Duration; let handle = thread::spawn(|| { for i in 1..5 { println!("子线程: {}", i); thread::sleep(Duration::from_millis(1)); } }); for i in 1..5 { println!("主线程: {}", i); thread::sleep(Duration::from_millis(1)); } handle.join().unwrap(); ``` > `join` 等待子线程结束。如果不调用 `join`,主线程可能先退出。 ## 32.2 move 闭包与线程 线程通常需要使用 `move` 闭包获取数据所有权: ```rust let v = vec![1, 2, 3]; let handle = thread::spawn(move || { println!("子线程持有: {:?}", v); }); handle.join().unwrap(); // println!("{:?}", v); // 错误:v 已被移动到子线程 ``` ## 32.3 通道 mpsc Rust 使用 `mpsc`(multiple producer, single consumer)通道在线程间传递消息: ```rust use std::sync::mpsc; use std::thread; let (tx, rx) = mpsc::channel(); thread::spawn(move || { let val = String::from("hi"); tx.send(val).unwrap(); // println!("{}", val); // 错误:val 已被发送,所有权转移 }); let received = rx.recv().unwrap(); println!("收到: {}", received); // 收到: hi ``` ## 32.4 多生产者 可以克隆发送端,让多个线程发送消息: ```rust use std::sync::mpsc; use std::thread; let (tx, rx) = mpsc::channel(); let tx1 = tx.clone(); thread::spawn(move || { tx.send(String::from("来自线程1")).unwrap(); }); thread::spawn(move || { tx1.send(String::from("来自线程2")).unwrap(); }); for received in rx { println!("收到: {}", received); } ``` ## 32.5 共享状态并发 使用 `Arc<Mutex<T>>` 在多线程间共享可变状态: ```rust use std::sync::{Arc, Mutex}; use std::thread; let counter = Arc::new(Mutex::new(0)); let mut handles = vec![]; for _ in 0..10 { let counter = Arc::clone(&counter); let handle = thread::spawn(move || { let mut num = counter.lock().unwrap(); *num += 1; }); handles.push(handle); } for handle in handles { handle.join().unwrap(); } println!("结果: {}", *counter.lock().unwrap()); ``` > `Mutex` 保护数据,任何时刻只有一个线程能修改。`Arc` 让多个线程共享 `Mutex` 的所有权。 ## 32.6 Send 与 Sync trait `Send` 和 `Sync` 是 Rust 并发安全的基石: - `Send`:类型可以安全地转移到另一个线程。 - `Sync`:类型可以安全地被多个线程同时引用(即 `&T` 是 `Send`)。 大多数 Rust 类型都实现了 `Send` 和 `Sync`。`Rc<T>` 不是 `Send` 也不是 `Sync`,因此不能跨线程。`RefCell<T>` 不是 `Sync`。 ## 32.7 小结 | 并发方式 | 类型 / 方法 | 说明 | | 创建线程 | `thread::spawn` | 新线程执行闭包 | | 等待线程 | `handle.join()` | 阻塞直到线程结束 | | 消息传递 | `mpsc::channel` | 发送端 `Sender`,接收端 `Receiver` | | 共享状态 | `Arc<Mutex<T>>` | 多线程共享可变数据 | | 线程安全 | `Send` / `Sync` | 编译时保证数据安全 | ## 32.8 思考题 1. 为什么线程闭包通常需要 `move`? 2. 通道中的 `send` 方法转移了什么? 3. 写一个程序,使用 `mpsc` 通道让一个线程发送 10 个数字,主线程接收并打印它们的平方。 登录 Detach Close 该主题尚不存在 您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。 rust/并发基础.txt 最后更改: 2026/08/12 23:57由 张叶安 登录