Rust 并发编程:舌战群儒
Rust 以“无畏并发”(Fearless Concurrency) 著称。编译器会帮你检查数据竞争 (Data Race)。
🧵 创建线程 (spawn)
使用 thread::spawn 创建新线程。
use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
for i in 1..10 {
println!("烈火奶奶骂了 {} 句", i);
thread::sleep(Duration::from_millis(1));
}
});
for i in 1..5 {
println!("包龙星回了 {} 句", i);
thread::sleep(Duration::from_millis(1));
}
handle.join().unwrap(); // 等待子线程结束
}
📨 消息传递 (Channel)
不要通过共享内存来通信,要通过通信来共享内存。
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("大人,常威打我!");
tx.send(val).unwrap();
});
let received = rx.recv().unwrap();
println!("收到消息: {}", received);
}
🔒 共享状态 (Mutex)
互斥锁 (Mutex) 保证同一时间只有一个线程能访问数据。
use std::sync::{Mutex, Arc};
use std::thread;
fn main() {
// Arc (Atomic Reference Counting) 用于多线程间共享所有权
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());
}