CentOS下Rust并发编程入门指南
一 环境准备
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | shsource $HOME/.cargo/envcargo --version、rustc --versioncargo new concurrent_demo && cd concurrent_democargo run、cargo build二 并发模型与最小示例
thread::spawn(|| { ... }) 创建线程handle.join().unwrap() 等待回收let (tx, rx) = mpsc::channel();tx.send(val).unwrap(); 发送;rx.recv().unwrap(); 接收let counter = Arc::new(Mutex::new(0));let c = Arc::clone(&counter); 在子线程中克隆let mut n = c.lock().unwrap(); *n += 1;tokio = { version = "1", features = ["full"] }#[tokio::main] async fn main()tokio::spawn(async { ... });常用 select!、定时器、信号处理等组合任务。三 示例汇总
use std::thread;
fn main() {
let h = thread::spawn(|| {
for i in 1..5 { println!("子线程: {}", i); }
});
for i in 1..3 { println!("主线程: {}", i); }
h.join().unwrap();
}
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || { tx.send("hi").unwrap(); });
let msg = rx.recv().unwrap();
println!("收到: {}", msg);
}
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!("结果: {}", *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];
while let Ok(n) = socket.read(&mut buf).await {
if n == 0 { break; }
if socket.write_all(&buf[..n]).await.is_err() { break; }
}
});
}
}
以上示例覆盖了 线程、通道、共享状态、异步并发 的常用入门写法,可直接在 CentOS 上 cargo run 运行。
四 实践建议与常见坑
ss -tlnp | grep 8080