Debian下Rust并发编程指南
一 环境准备与项目初始化
source $HOME/.cargo/env 使环境变量生效。随后可用 cargo new 创建项目、cargo build 构建、cargo run 运行。rustup update。二 并发模型与适用场景
Arc 提供线程安全的引用计数,Mutex/RwLock 提供互斥/读写保护,Atomic* 提供无锁的原子操作。async/.await 语法需要配合运行时(如 Tokio)执行异步任务与 I/O。三 快速上手示例
Arc<Mutex<T>> 保护临界区,避免数据竞争。AtomicUsize 结合合适的 Ordering 完成计数。示例清单(可直接运行,按需选择片段):
// 1) 线程
use std::thread;
let h = thread::spawn(|| println!("Hello from thread"));
h.join().unwrap();
// 2) 通道 MPSC
use std::sync::mpsc;
use std::thread;
let (tx, rx) = mpsc::channel();
thread::spawn(move || tx.send("hi").unwrap());
println!("Got: {}", rx.recv().unwrap());
// 3) 共享状态 Arc<Mutex<T>>
use std::sync::{Arc, Mutex};
use std::thread;
let c = Arc::new(Mutex::new(0));
let mut hs = vec![];
for _ in 0..10 {
let c = Arc::clone(&c);
hs.push(thread::spawn(move || *c.lock().unwrap() += 1));
}
for h in hs { h.join().unwrap(); }
println!("Result: {}", *c.lock().unwrap());
// 4) 原子计数
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
let cnt = AtomicUsize::new(0);
let mut hs = vec![];
for _ in 0..10 {
hs.push(thread::spawn(move || cnt.fetch_add(1, Ordering::SeqCst)));
}
for h in hs { h.join().unwrap(); }
println!("Atomic result: {}", cnt.load(Ordering::SeqCst));
// 5) 异步并发(需 Cargo.toml 添加: tokio = { version = "1", features = ["full"] })
/*
[dependencies]
tokio = { version = "1", features = ["full"] }
*/
use tokio; // 使用 #[tokio::main] 或手动构建运行时
以上示例覆盖了线程、通道、共享状态、原子操作与异步并发的常用模式,可作为在 Debian 上的起步模板。
四 性能优化与排错建议
cargo build --release -C opt-level=3。Cargo.toml 的 [profile.release] 中设置 lto = true)。#[repr(align(64))])。