1. 安装Rust工具链
在CentOS上安装Rust需通过官方脚本rustup完成。首先确保系统已安装curl(若未安装,可通过sudo yum install curl -y安装),然后执行以下命令:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
安装完成后,将Rust工具链添加到环境变量中:
source $HOME/.cargo/env
验证安装是否成功:
rustc --version # 查看Rust编译器版本
cargo --version # 查看Cargo包管理器版本
2. 配置系统依赖与环境
Rust并发编程需依赖系统工具链(如gcc)和库,通过以下命令安装:
sudo yum install gcc cmake make -y
为提升依赖下载速度,建议配置国内镜像源(如中科大镜像):
# 设置rustup镜像
export rustup_dist_server=https://mirrors.ustc.edu.cn/rust-static
export rustup_update_root=https://mirrors.ustc.edu.cn/rust-static/rustup
# 配置Cargo镜像(在~/.cargo/config中添加)
mkdir -p ~/.cargo
cat <<EOF > ~/.cargo/config
[source.crates-io]
replace-with = 'ustc'
[source.ustc]
registry = "git://mirrors.ustc.edu.cn/crates.io-index"
EOF
3. 创建Rust并发项目
使用Cargo创建新项目,选择适合的并发场景(如线程、异步):
cargo new concurrency_demo # 创建名为concurrency_demo的项目
cd concurrency_demo
初始化后,项目结构如下:
concurrency_demo/
├── Cargo.toml # 依赖配置文件
└── src/
└── main.rs # 主程序入口
4. 编写并发代码(三种常见模型)
Rust的并发模型以“安全”为核心,以下是三种典型方式的实现:
使用std::thread模块创建线程,通过move关键字转移所有权,避免数据竞争:
use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
for i in 1..5 {
println!("子线程: {}", i);
thread::sleep(Duration::from_millis(500));
}
});
for i in 1..3 {
println!("主线程: {}", i);
thread::sleep(Duration::from_millis(500));
}
handle.join().unwrap(); // 等待子线程结束
}
使用std::sync::mpsc模块的通道(Channel)实现线程间安全通信,避免直接共享数据:
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel(); // 创建通道(tx: 发送端, rx: 接收端)
thread::spawn(move || {
let val = String::from("Hello from thread!");
tx.send(val).unwrap(); // 发送数据(val的所有权转移至通道)
});
let received = rx.recv().unwrap(); // 接收数据(阻塞直到收到消息)
println!("主线程收到: {}", received);
}
使用tokio异步运行时(需添加依赖),通过async/await语法处理高并发IO任务(如网络请求):
首先,在Cargo.toml中添加tokio依赖:
[dependencies]
tokio = { version = "1", features = ["full"] }
然后编写异步代码:
use tokio::net::TcpListener;
use tokio::prelude::*;
#[tokio::main] // 宏:将main函数转换为异步函数
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let listener = TcpListener::bind("127.0.0.1:8080").await?; // 绑定本地端口
loop {
let (mut socket, addr) = listener.accept().await?; // 异步接受连接
println!("收到来自 {} 的连接", addr);
tokio::spawn(async move { // 为每个连接创建异步任务
let mut buf = [0; 1024]; // 缓冲区
match socket.read(&mut buf).await { // 异步读取数据
Ok(n) if n == 0 => return, // 连接关闭
Ok(n) => {
if socket.write_all(&buf[0..n]).await.is_err() { // 异步写回数据
eprintln!("写入数据失败");
}
}
Err(e) => {
eprintln!("读取数据失败: {:?}", e);
}
}
});
}
}
5. 编译与运行项目
使用Cargo编译并运行项目(默认调试模式):
cargo run # 编译并运行(Debug模式)
若需发布模式(优化性能),执行:
cargo build --release # 编译(Release模式,优化级别为3)
./target/release/concurrency_demo # 运行
6. 并发编程注意事项
std::sync::Mutex(互斥锁)或Arc<Mutex<T>>(原子引用计数的互斥锁),避免死锁。rayon库(数据并行);对于IO密集型任务,优先选择异步编程(如tokio)。