目录

32. 并发基础

学习目标

32.1 创建线程

使用 std::thread::spawn 创建新线程:

snippet.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 闭包获取数据所有权:

snippet.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)通道在线程间传递消息:

snippet.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 多生产者

可以克隆发送端,让多个线程发送消息:

snippet.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>> 在多线程间共享可变状态:

snippet.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 并发安全的基石:

大多数 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 个数字,主线程接收并打印它们的平方。