在Debian上进行Rust并发编程,需先安装Rust工具链,再根据场景选择并发模式,核心步骤如下:
通过rustup
安装Rust,确保环境变量配置正确:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env # 配置环境变量
rustc --version # 验证安装
使用std::thread
创建线程,适合CPU密集型任务:
use std::thread;
fn main() {
let handle = thread::spawn(|| {
println!("子线程执行");
});
handle.join().unwrap(); // 等待线程结束
}
共享数据:通过Arc
(原子引用计数)+ Mutex
(互斥锁)实现线程安全:
use std::sync::{Arc, Mutex};
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
handles.push(thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
}));
}
println!("最终计数: {}", *counter.lock().unwrap());
使用std::sync::mpsc
或crossbeam
实现线程间通信:
use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
tx.send("Hello from thread").unwrap();
});
println!("收到: {}", rx.recv().unwrap());
crossbeam
支持高性能无锁通道,适合高吞吐场景:
use crossbeam::channel::unbounded;
let (tx, rx) = unbounded();
tx.send(42).unwrap();
println!("接收: {}", rx.recv().unwrap());
适用于I/O密集型任务(如网络请求、文件操作),需在Cargo.toml
添加依赖:
[dependencies]
tokio = { version = "1", features = ["full"] }
示例:异步HTTP请求
use tokio::task;
use reqwest::Error;
#[tokio::main]
async fn main() -> Result<(), Error> {
let urls = vec!["https://example.com"];
let tasks: Vec<_> = urls.into_iter().map(|url| {
task::spawn(async move {
let resp = reqwest::get(url).await?;
println!("响应: {:?}", resp);
})
}).collect();
for task in tasks {
task.await??;
}
Ok(())
}
use rayon::prelude::*;
(0..100).into_par_iter().for_each(|i| {
println!("处理: {}", i);
});
crossbeam::atomic
或dashmap
避免锁开销:use crossbeam::atomic::AtomicCell;
let data = AtomicCell::new(0);
data.fetch_add(1);
Arc+Mutex
或Atomic
类型,编译器会检查潜在竞争。tokio-console
监控异步任务,或loom
进行并发测试。以上内容参考自,可根据具体需求选择合适方案。