在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并發編程實踐,可根據具體需求選擇合適方案。