目录
什么是 Rust 并发编程
Rust 并发编程是指利用多线程或异步机制,使程序在多个任务间并行执行。Rust 通过所有权和类型系统,确保并发代码的内存安全和数据竞争的避免。
为什么要使用并发编程
- 性能提升:利用多核处理器并行处理任务。
- 响应性:在等待 I/O 时执行其他操作。
- 资源利用:优化 CPU 和内存使用。
- 安全保证:Rust 防止数据竞争和死锁。
Rust 的并发模型
- 线程:
- 使用
std::thread
创建独立执行单元。 - 适合 CPU 密集型任务。
- 异步 (Async):
- 使用
async
/await
和运行时(如tokio
)。 - 适合 I/O 密集型任务。
- 所有权保障:
Send
trait:值可跨线程转移。Sync
trait:值可安全共享。
线程操作
- 创建线程:
thread::spawn
。 - 等待线程:
join()
。 - 线程间传递数据:使用
move
闭包。
use std::thread;
thread::spawn(|| {
println!("Hello from thread!");
});
线程同步与通信
- 互斥锁 (Mutex):
std::sync::Mutex
保护共享数据。- 读写锁 (RwLock):
std::sync::RwLock
允许多读单写。- 通道 (Channel):
std::sync::mpsc
用于线程间消息传递。
use std::sync::Mutex;
let mutex = Mutex::new(0);
代码示例
基本线程
use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
for i in 1..5 {
println!("Thread: {}", i);
thread::sleep(Duration::from_millis(100));
}
});
for i in 1..5 {
println!("Main: {}", i);
thread::sleep(Duration::from_millis(100));
}
handle.join().unwrap();
}
运行结果(顺序可能不同):
Main: 1
Thread: 1
Main: 2
Thread: 2
Main: 3
Thread: 3
Main: 4
Thread: 4
Mutex 同步
use std::sync::{Mutex, Arc};
use std::thread;
fn main() {
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!("Result: {}", *counter.lock().unwrap());
}
运行结果:
Result: 10
通道通信
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("Hello from thread!");
tx.send(val).unwrap();
});
let received = rx.recv().unwrap();
println!("Received: {}", received);
}
运行结果:
Received: Hello from thread!
参考资料与出站链接
- 官方文档:
- 学习资源:
- 社区支持:
发表回复