在 Debian 上配置 Rust 并发编程
一 环境准备
二 选择并发模型与依赖配置
三 最小可用示例
线程 + 通道 use std::sync::mpsc; use std::thread;
fn main() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { tx.send(“hello from thread”).unwrap(); }); println!(“received: {}”, rx.recv().unwrap()); }
线程 + 共享状态(Arc + Mutex) use std::sync::{Arc, Mutex}; use std::thread;
fn main() { let c = Arc::new(Mutex::new(0)); let mut handles = vec![]; for _ in 0…10 { let c = Arc::clone(&c); handles.push(thread::spawn(move || { *c.lock().unwrap() += 1; })); } for h in handles { h.join().unwrap(); } println!(“counter = {}”, *c.lock().unwrap()); }
异步并发(tokio) // Cargo.toml // [dependencies] // tokio = { version = “1”, features = [“rt”, “net”] }
use tokio;
#[tokio::main] async fn main() { println!(“Hello from async main”); tokio::time::sleep(tokio::time::Duration::from_millis(100)).await; }
四 性能优化与系统调优
五 调试与常见坑