主题
线程与多线程
Rust 通过标准库中的 std::thread
模块支持创建和管理线程,实现并发任务。
创建线程
使用 thread::spawn
启动新线程:
rust
use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
for i in 1..5 {
println!("子线程运行第 {} 次", i);
thread::sleep(Duration::from_millis(500));
}
});
for i in 1..3 {
println!("主线程运行第 {} 次", i);
thread::sleep(Duration::from_millis(700));
}
handle.join().unwrap(); // 等待子线程结束
}
线程安全与所有权
Rust 的所有权系统确保数据在线程间安全共享,避免数据竞争。
共享状态的多线程
使用互斥锁 Mutex
和原子引用计数 Arc
共享可变数据:
rust
use std::sync::{Arc, Mutex};
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!("计数器的值: {}", *counter.lock().unwrap());
}