debian

Debian下Rust并发编程指南

小樊
31
2026-01-03 15:14:01
栏目: 编程语言

Debian下Rust并发编程指南

一 环境准备与项目初始化

二 并发模型与适用场景

三 快速上手示例

示例清单(可直接运行,按需选择片段):

// 1) 线程
use std::thread;

let h = thread::spawn(|| println!("Hello from thread"));
h.join().unwrap();

// 2) 通道 MPSC
use std::sync::mpsc;
use std::thread;

let (tx, rx) = mpsc::channel();
thread::spawn(move || tx.send("hi").unwrap());
println!("Got: {}", rx.recv().unwrap());

// 3) 共享状态 Arc<Mutex<T>>
use std::sync::{Arc, Mutex};
use std::thread;

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!("Result: {}", *c.lock().unwrap());

// 4) 原子计数
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;

let cnt = AtomicUsize::new(0);
let mut hs = vec![];
for _ in 0..10 {
    hs.push(thread::spawn(move || cnt.fetch_add(1, Ordering::SeqCst)));
}
for h in hs { h.join().unwrap(); }
println!("Atomic result: {}", cnt.load(Ordering::SeqCst));

// 5) 异步并发(需 Cargo.toml 添加: tokio = { version = "1", features = ["full"] })
/*
[dependencies]
tokio = { version = "1", features = ["full"] }
*/
use tokio; // 使用 #[tokio::main] 或手动构建运行时

以上示例覆盖了线程、通道、共享状态、原子操作与异步并发的常用模式,可作为在 Debian 上的起步模板。

四 性能优化与排错建议

0
看了该问题的人还看了