目录

Rust 多线程与 Channel

Rust 的并发哲学是「无畏并发(fearless concurrency)」:编译器在编译期就帮你避开数据竞争。线程用 std::thread,线程间通信靠 Channel

https://img.zhaojq.top/20260804234640654.png
Rust 并发与异步

启动线程

use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..=3 {
            println!("子线程: {}", i);
        }
    });
    handle.join().unwrap(); // 等子线程结束
    println!("主线程结束");
}

move 闭包转移所有权

线程里的闭包常需 move 把数据「搬」进线程:

use std::thread;

fn main() {
    let data = vec![1, 2, 3];
    let h = thread::spawn(move || {
        println!("拿到数据: {:?}", data);
    });
    h.join().unwrap();
}

用 Channel 传递消息

Channel 是「发送端 + 接收端」的管道,遵循 Rust 的「所有权转移」:

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();
    thread::spawn(move || {
        tx.send("你好 from 子线程").unwrap();
    });
    let msg = rx.recv().unwrap(); // 阻塞接收
    println!("收到: {}", msg);
}

小结

  • thread::spawn 开线程,join 等待。
  • move 把值的所有权搬进线程,避免悬垂引用。
  • Channel(mpsc)用消息传递代替共享内存,更安全。

➡️ 10. async/await 与 Tokio