debian

Rust在Debian上如何进行并发编程

小樊
36
2025-08-10 01:15:13
栏目: 编程语言

在Debian上进行Rust并发编程,需先安装Rust工具链,再根据场景选择并发模式,核心步骤如下:

1. 安装Rust

通过rustup安装Rust,确保环境变量配置正确:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env  # 配置环境变量
rustc --version  # 验证安装

2. 并发编程模式

(1)多线程(标准库)

使用std::thread创建线程,适合CPU密集型任务:

use std::thread;
fn main() {
    let handle = thread::spawn(|| {
        println!("子线程执行");
    });
    handle.join().unwrap(); // 等待线程结束
}

共享数据:通过Arc(原子引用计数)+ Mutex(互斥锁)实现线程安全:

use std::sync::{Arc, Mutex};
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());

(2)消息传递(通道)

使用std::sync::mpsccrossbeam实现线程间通信:

use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
    tx.send("Hello from thread").unwrap();
});
println!("收到: {}", rx.recv().unwrap());

crossbeam支持高性能无锁通道,适合高吞吐场景:

use crossbeam::channel::unbounded;
let (tx, rx) = unbounded();
tx.send(42).unwrap();
println!("接收: {}", rx.recv().unwrap());

(3)异步编程(Tokio/async-std)

适用于I/O密集型任务(如网络请求、文件操作),需在Cargo.toml添加依赖:

[dependencies]
tokio = { version = "1", features = ["full"] }

示例:异步HTTP请求

use tokio::task;
use reqwest::Error;
#[tokio::main]
async fn main() -> Result<(), Error> {
    let urls = vec!["https://example.com"];
    let tasks: Vec<_> = urls.into_iter().map(|url| {
        task::spawn(async move {
            let resp = reqwest::get(url).await?;
            println!("响应: {:?}", resp);
        })
    }).collect();
    for task in tasks {
        task.await??;
    }
    Ok(())
}

(4)高级模式

3. 注意事项

以上内容参考自,可根据具体需求选择合适方案。

0
看了该问题的人还看了