thread::spawn ​

核心概念 ​

thread::spawn 是 Rust 中创建新线程的核心函数,定义在 std::thread 模块中。它接受一个实现了 FnOnce() -> T 的闭包,其中 T 必须满足 Send + 'static。Send 约束确保闭包可以安全地跨线程传递,'static 约束确保闭包不包含任何非静态引用(因为线程的生命周期不确定)。spawn 返回一个 JoinHandle<T>,用于等待线程完成和获取返回值。

rust
use std::thread;

fn main() {
    // spawn 的函数签名(简化版):
    // pub fn spawn<F, T>(f: F) -> JoinHandle<T>
    // where
    //     F: FnOnce() -> T + Send + 'static,
    //     T: Send + 'static

    // 最简单的 spawn:无参数无返回值
    let handle = thread::spawn(|| {
        println!("子线程运行中");
    });
    handle.join().unwrap();

    // 带返回值的 spawn
    let handle = thread::spawn(|| {
        let result = 42 * 2;
        result  // 返回值类型 T = i32
    });
    let value = handle.join().unwrap();
    println!("线程返回: {}", value);

    // 带 move 的 spawn
    let name = String::from("Rust");
    let handle = thread::spawn(move || {
        format!("Hello, {}!", name)
    });
    let greeting = handle.join().unwrap();
    println!("{}", greeting);
}

spawn 的类型约束 ​

rust
use std::thread;

fn main() {
    // Send 约束:闭包和捕获的数据必须能安全跨线程传递
    // 大多数类型都实现了 Send,但 Rc<T> 没有
    // use std::rc::Rc;
    // let rc = Rc::new(42);
    // thread::spawn(move || println!("{}", rc));  // 编译错误:Rc 不是 Send

    // 'static 约束:闭包不能借用局部变量
    // let local = String::from("局部");
    // thread::spawn(|| println!("{}", local));  // 编译错误:借用非 'static

    // 正确做法:move 获取所有权
    let data = String::from("数据");
    let handle = thread::spawn(move || {
        println!("{}", data);  // data 被移入线程
    });
    handle.join().unwrap();

    // 'static 引用可以被借用
    static GLOBAL: &str = "全局常量";
    let handle = thread::spawn(|| {
        println!("{}", GLOBAL);  // 'static 引用,不需要 move
    });
    handle.join().unwrap();

    // 字符串字面量也是 'static
    let handle = thread::spawn(|| {
        let s: &'static str = "字面量";
        println!("{}", s);
    });
    handle.join().unwrap();
}

spawn 与闭包的关系 ​

rust
use std::thread;

fn main() {
    // FnOnce:spawn 接受 FnOnce,闭包只会被调用一次
    let data = vec![1, 2, 3];
    let handle = thread::spawn(move || {
        // data 被 move 进来,可以消耗
        let sum: i32 = data.into_iter().sum();
        sum
    });
    println!("总和: {}", handle.join().unwrap());

    // 传入普通函数(函数指针也实现了 FnOnce + Send + 'static)
    fn worker() -> String {
        String::from("工作完成")
    }

    let handle = thread::spawn(worker);
    println!("{}", handle.join().unwrap());

    // 传入复杂闭包
    let factor = 10;
    let items = vec![1, 2, 3, 4, 5];
    let handle = thread::spawn(move || {
        items.iter()
            .map(|&x| x * factor)
            .collect::<Vec<i32>>()
    });
    println!("结果: {:?}", handle.join().unwrap());
}

批量 spawn ​

rust
use std::thread;
use std::time::Duration;

fn main() {
    // 批量创建线程
    let mut handles = Vec::new();

    for i in 0..8 {
        let handle = thread::spawn(move || {
            // 模拟不同耗时的任务
            let sleep_ms = 50 * ((i % 3) as u64 + 1);
            thread::sleep(Duration::from_millis(sleep_ms));
            println!("线程 {} 完成 (耗时 {}ms)", i, sleep_ms);
            i * i
        });
        handles.push(handle);
    }

    // 按顺序等待所有线程
    let results: Vec<i32> = handles.into_iter()
        .map(|h| h.join().unwrap())
        .collect();
    println!("所有结果: {:?}", results);

    // 用 map 直接创建并收集
    let handles: Vec<_> = (0..5)
        .map(|i| {
            thread::spawn(move || {
                format!("线程{}的结果", i)
            })
        })
        .collect();

    for handle in handles {
        println!("{}", handle.join().unwrap());
    }
}

spawn 与 Builder 的对比 ​

rust
use std::thread;

fn main() {
    // thread::spawn:快捷方式,使用默认配置
    let h1 = thread::spawn(|| "默认线程");
    println!("{}", h1.join().unwrap());

    // thread::Builder:可以自定义线程属性
    let h2 = thread::Builder::new()
        .name("自定义线程".to_string())
        .stack_size(2 * 1024 * 1024)  // 2MB 栈
        .spawn(|| {
            let name = thread::current().name().unwrap_or("未命名").to_string();
            format!("我是 '{}'", name)
        })
        .unwrap();
    println!("{}", h2.join().unwrap());

    // Builder::spawn 返回 io::Result<JoinHandle>
    // thread::spawn 直接返回 JoinHandle(创建失败会 panic)
    let result = thread::Builder::new()
        .name("可能失败".to_string())
        .spawn(|| 42);

    match result {
        Ok(handle) => println!("线程创建成功: {}", handle.join().unwrap()),
        Err(e) => println!("线程创建失败: {}", e),
    }
}
特性thread::spawnthread::Builder::spawn
线程名称无可设置
栈大小系统默认可自定义
返回值JoinHandle<T>io::Result<JoinHandle<T>>
创建失败panic返回 Err
使用场景简单快速需要定制化

基本示例 ​

用 spawn 实现并行数据处理:

rust
use std::thread;
use std::time::Instant;

fn main() {
    // 生成大量数据
    let data: Vec<i32> = (1..=1_000_000).collect();
    let num_threads = 4;
    let chunk_size = data.len() / num_threads;

    // 并行求和
    let start = Instant::now();

    let handles: Vec<_> = data.chunks(chunk_size)
        .enumerate()
        .map(|(i, chunk)| {
            let chunk_owned: Vec<i32> = chunk.to_vec();
            thread::spawn(move || {
                let sum: i64 = chunk_owned.iter().map(|&x| x as i64).sum();
                println!("  线程{}: 处理 {} 个元素, 部分和 = {}", i, chunk_owned.len(), sum);
                sum
            })
        })
        .collect();

    let total: i64 = handles.into_iter()
        .map(|h| h.join().unwrap())
        .sum();

    let parallel_time = start.elapsed();

    // 串行求和对比
    let start = Instant::now();
    let serial_total: i64 = data.iter().map(|&x| x as i64).sum();
    let serial_time = start.elapsed();

    println!("\n并行总和: {}, 耗时: {:?}", total, parallel_time);
    println!("串行总和: {}, 耗时: {:?}", serial_total, serial_time);
    println!("结果一致: {}", total == serial_total);

    // 并行处理字符串
    let words = vec![
        vec!["hello", "world"],
        vec!["rust", "is", "fast"],
        vec!["concurrent", "programming"],
    ];

    let handles: Vec<_> = words.into_iter()
        .map(|group| {
            thread::spawn(move || {
                group.iter()
                    .map(|w| w.to_uppercase())
                    .collect::<Vec<String>>()
            })
        })
        .collect();

    let results: Vec<Vec<String>> = handles.into_iter()
        .map(|h| h.join().unwrap())
        .collect();

    println!("\n并行大写转换:");
    for group in &results {
        println!("  {:?}", group);
    }
}

常见问题 ​

问题一:为什么 spawn 要求 'static?

线程的生命周期是不确定的,可能比创建它的函数活得更久。如果闭包借用了栈上的局部变量,局部变量释放后引用就悬空了。'static 确保闭包持有的所有数据要么是拥有所有权的(通过 move),要么是全局/静态的。

问题二:spawn 的闭包 panic 了怎么办?

子线程 panic 不会影响其他线程。join() 会返回 Err,里面包含 panic 的信息。如果不调用 join(),panic 会被默默忽略(只在 stderr 打印错误信息)。

问题三:spawn 和 async 有什么区别?

spawn 创建操作系统线程,适合 CPU 密集型任务,每个线程有独立的栈(几 MB)。async 创建轻量级任务(Future),适合 IO 密集型任务,成千上万个任务共享少量线程。

问题四:能在 spawn 中传递引用吗?

不能直接传递局部变量的引用('static 约束)。可以用 Arc 共享数据,或者用 std::thread::scope(Rust 1.63+)在限定作用域内安全借用。

适用场景 ​

  • 并行计算:将大任务分割为多个子任务
  • 后台处理:不阻塞主线程的长时间操作
  • 并发 IO:同时处理多个文件或网络请求
  • 定时任务:在独立线程中执行周期性工作

注意事项 ​

  • 闭包通常需要 move 获取数据所有权
  • 闭包和返回值必须满足 Send + 'static
  • Rc<T> 不是 Send,跨线程用 Arc<T>
  • thread::spawn 创建失败会 panic,Builder::spawn 返回 Result
  • 创建线程有系统开销,不适合大量短小任务
  • 子线程 panic 不影响其他线程,但 join() 会返回 Err

总结 ​

thread::spawn 接受一个 FnOnce() -> T + Send + 'static 的闭包,创建新的操作系统线程并返回 JoinHandle<T>。Send 保证闭包可以安全跨线程传递,'static 保证不借用局部变量。闭包通常需要 move 获取数据所有权。JoinHandle 用于等待线程完成(join())和获取返回值。thread::Builder 提供更多控制选项(线程名称、栈大小)并返回 Result。spawn 适合 CPU 密集型并行任务和后台处理,对于大量轻量级 IO 任务更推荐 async。