在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(); // 等待线程结束
}
利用std::sync::mpsc
实现线程间通信,支持多生产者单消费者:
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
tx.send("消息内容").unwrap();
});
println!("收到: {}", rx.recv().unwrap());
}
基于tokio
运行时,使用async/await
实现高并发I/O:
Cargo.toml
添加依赖:[dependencies]
tokio = { version = "1", features = ["full"] }
use tokio::net::TcpListener;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let listener = TcpListener::bind("127.0.0.1:8080").await?;
loop {
let (mut socket, _) = listener.accept().await?;
tokio::spawn(async move {
let mut buf = [0; 1024];
if let Ok(n) = socket.read(&mut buf).await {
socket.write_all(&buf[..n]).await.unwrap();
}
});
}
}
使用Arc
(原子引用计数)+Mutex
(互斥锁)安全共享数据:
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);
handles.push(thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
}));
}
println!("最终结果: {}", *counter.lock().unwrap());
}
rayon
)。gdb
或lldb
调试多线程程序,或使用tokio-console
监控异步任务。以上内容综合自Debian环境下的Rust并发编程实践,可根据具体需求选择合适方案。