Rust在Debian的并发编程支持
一 环境准备与工具链
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | shsource $HOME/.cargo/envrustc --version、cargo --versioncargo new concurrency-demo && cd concurrency-democargo run 构建并运行二 并发模型与关键原语
tokio = { version = "1", features = ["full"] },使用 #[tokio::main] 入口。三 最小可用示例
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || tx.send("hello from thread").unwrap());
println!("got: {}", rx.recv().unwrap());
}
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
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!("counter = {}", *c.lock().unwrap());
}
[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 {
let _ = socket.write_all(&buf[..n]).await;
}
});
}
}
以上示例覆盖了 线程、通道、共享状态 与 异步 I/O 的主流用法,可直接在 Debian 上编译运行。
四 实践建议与排错