join 等待完成 ​

核心概念 ​

join() 是 JoinHandle<T> 的方法,调用后会阻塞当前线程,直到目标线程运行完毕。它的签名是 fn join(self) -> Result<T, Box<dyn Any + Send>>,注意参数是 self(消耗所有权),所以一个 JoinHandle 只能 join 一次。Ok(T) 包含线程闭包的返回值,Err 包含线程 panic 时抛出的信息。join 是确保子线程完成、收集结果和检测错误的核心手段。

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

fn main() {
    let handle = thread::spawn(|| {
        thread::sleep(Duration::from_millis(200));
        println!("子线程完成");
        100
    });

    println!("主线程等待...");

    // join() 阻塞直到子线程完成,并返回结果
    let result = handle.join().unwrap();
    println!("子线程返回: {}", result);

    // 此时子线程一定已经完成
    println!("继续主线程的工作");
}

join 的时机对执行顺序的影响 ​

rust
use std::thread;
use std::time::{Duration, Instant};

fn main() {
    let start = Instant::now();

    // === 立即 join(串行效果)===
    println!("=== 立即 join ===");
    let h1 = thread::spawn(|| {
        thread::sleep(Duration::from_millis(200));
        "任务A"
    });
    h1.join().unwrap();  // 等A完成才继续

    let h2 = thread::spawn(|| {
        thread::sleep(Duration::from_millis(200));
        "任务B"
    });
    h2.join().unwrap();  // 等B完成才继续

    println!("立即join耗时: {:?}", start.elapsed());
    // 约 400ms(串行)

    // === 延迟 join(并行效果)===
    let start = Instant::now();
    println!("\n=== 延迟 join ===");

    // 先启动所有线程
    let h1 = thread::spawn(|| {
        thread::sleep(Duration::from_millis(200));
        "任务A"
    });
    let h2 = thread::spawn(|| {
        thread::sleep(Duration::from_millis(200));
        "任务B"
    });

    // 之后再 join
    let r1 = h1.join().unwrap();
    let r2 = h2.join().unwrap();
    println!("结果: {}, {}", r1, r2);
    println!("延迟join耗时: {:?}", start.elapsed());
    // 约 200ms(并行)
}

join 处理线程 panic ​

rust
use std::thread;

fn main() {
    // 正常线程
    let h1 = thread::spawn(|| "正常完成");
    match h1.join() {
        Ok(val) => println!("成功: {}", val),
        Err(_) => println!("失败"),
    }

    // panic 线程
    let h2 = thread::spawn(|| -> i32 {
        panic!("发生错误");
    });
    match h2.join() {
        Ok(val) => println!("成功: {}", val),
        Err(e) => {
            // 提取 panic 信息
            if let Some(s) = e.downcast_ref::<&str>() {
                println!("线程 panic: {}", s);
            } else if let Some(s) = e.downcast_ref::<String>() {
                println!("线程 panic: {}", s);
            } else {
                println!("线程 panic: 未知类型");
            }
        }
    }

    // 批量 join 时的错误处理
    let handles: Vec<_> = (0..6).map(|i| {
        thread::spawn(move || -> Result<String, String> {
            if i == 2 || i == 4 {
                Err(format!("任务{}遇到业务错误", i))
            } else {
                Ok(format!("任务{}完成", i))
            }
        })
    }).collect();

    println!("\n批量任务:");
    for (i, handle) in handles.into_iter().enumerate() {
        match handle.join() {
            Ok(Ok(msg)) => println!("  线程{}: {}", i, msg),
            Ok(Err(msg)) => println!("  线程{}: 业务错误 - {}", i, msg),
            Err(_) => println!("  线程{}: panic!", i),
        }
    }
}

join 的顺序与结果收集 ​

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

fn main() {
    // 线程完成顺序和 join 顺序无关
    // join 按照调用顺序阻塞
    let handles: Vec<_> = vec![300, 100, 200, 50, 150]
        .into_iter()
        .enumerate()
        .map(|(i, ms)| {
            thread::spawn(move || {
                thread::sleep(Duration::from_millis(ms));
                println!("  线程{} 完成 ({}ms)", i, ms);
                (i, ms)
            })
        })
        .collect();

    println!("按创建顺序 join:");
    let mut results = Vec::new();
    for handle in handles {
        let (id, ms) = handle.join().unwrap();
        results.push((id, ms));
    }
    println!("收集顺序: {:?}", results);
    // 结果按 join 顺序排列(0,1,2,3,4),不管哪个先完成

    // 如果只关心所有线程都完成,不关心顺序
    let handles: Vec<_> = (0..5).map(|i| {
        thread::spawn(move || i * i)
    }).collect();

    let sum: i32 = handles.into_iter()
        .map(|h| h.join().unwrap())
        .sum();
    println!("\n所有结果之和: {}", sum);
}

不 join 的后果 ​

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

fn main() {
    // 不 join 的线程在主线程结束时可能被强制终止
    println!("=== 不 join 的线程 ===");

    thread::spawn(|| {
        println!("  短任务: 开始");
        thread::sleep(Duration::from_millis(10));
        println!("  短任务: 完成");  // 通常能完成
    });

    thread::spawn(|| {
        println!("  长任务: 开始");
        thread::sleep(Duration::from_millis(5000));
        println!("  长任务: 完成");  // 可能不会打印!
    });

    // 主线程只等一小段时间
    thread::sleep(Duration::from_millis(50));
    println!("主线程结束 — 长任务可能被终止了");

    // 安全做法:总是 join 重要的线程
    println!("\n=== 安全做法 ===");
    let important = thread::spawn(|| {
        thread::sleep(Duration::from_millis(100));
        println!("  重要任务完成");
        "重要结果"
    });

    let result = important.join().unwrap();
    println!("收到: {}", result);
}

基本示例 ​

用 join 实现一个分段并行计算框架:

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

// 并行 map-reduce
fn parallel_map_reduce<T, R, M, RE>(
    data: Vec<T>,
    num_threads: usize,
    map_fn: M,
    reduce_fn: RE,
    initial: R,
) -> R
where
    T: Send + 'static,
    R: Send + 'static + Clone,
    M: Fn(T) -> R + Send + 'static + Clone,
    RE: Fn(R, R) -> R,
{
    let chunk_size = (data.len() + num_threads - 1) / num_threads;

    // 分发任务到多个线程
    let handles: Vec<_> = data.into_iter()
        .collect::<Vec<_>>()
        .chunks(chunk_size)
        .map(|chunk| {
            let chunk_owned: Vec<T> = chunk.to_vec();
            let map_fn = map_fn.clone();
            let init = initial.clone();
            thread::spawn(move || {
                chunk_owned.into_iter()
                    .map(|item| map_fn(item))
                    .fold(init, |acc, val| {
                        // 这里简单地用最后一个值,实际用 reduce_fn 在外层合并
                        val
                    })
            })
        })
        .collect();

    // join 所有线程并 reduce
    handles.into_iter()
        .map(|h| h.join().unwrap())
        .fold(initial, |acc, val| reduce_fn(acc, val))
}

fn main() {
    let start = Instant::now();

    // 并行求和
    let data: Vec<i64> = (1..=1_000_000).collect();
    let num_threads = 4;
    let chunk_size = data.len() / num_threads;

    let handles: Vec<_> = data.chunks(chunk_size)
        .enumerate()
        .map(|(i, chunk)| {
            let chunk_vec: Vec<i64> = chunk.to_vec();
            thread::spawn(move || {
                let partial_sum: i64 = chunk_vec.iter().sum();
                println!("  段{}: {} 个元素, 部分和={}", i, chunk_vec.len(), partial_sum);
                partial_sum
            })
        })
        .collect();

    // join 收集所有部分和
    let total: i64 = handles.into_iter()
        .map(|h| h.join().unwrap())
        .sum();

    println!("总和: {}", total);
    println!("耗时: {:?}", start.elapsed());

    // 验证
    let expected: i64 = (1..=1_000_000).sum();
    println!("验证: {} == {} → {}", total, expected, total == expected);

    // 并行查找
    println!("\n=== 并行查找 ===");
    let data: Vec<i32> = (0..10_000).collect();
    let target = 7777;

    let handles: Vec<_> = data.chunks(2500)
        .enumerate()
        .map(|(i, chunk)| {
            let chunk_vec: Vec<i32> = chunk.to_vec();
            let offset = i * 2500;
            thread::spawn(move || {
                chunk_vec.iter()
                    .position(|&x| x == target)
                    .map(|pos| pos + offset)
            })
        })
        .collect();

    let position = handles.into_iter()
        .filter_map(|h| h.join().unwrap())
        .next();

    println!("目标 {} 在位置: {:?}", target, position);
}

常见问题 ​

问题一:join 可以设置超时吗?

标准库的 join() 不支持超时。如果需要超时功能,可以用通道(mpsc::channel)配合 recv_timeout,或者使用第三方库。

问题二:多个 join 的顺序重要吗?

如果只关心"所有线程都完成",顺序不重要。但 join 的顺序决定了结果的收集顺序。先 join 的 handle 会先返回结果(即使那个线程还没完成,当前线程会等它)。

问题三:join 后线程的资源会被释放吗?

是的。join() 返回后,线程的栈空间和操作系统资源会被释放。如果不 join 也不 detach,资源会在 JoinHandle drop 时由操作系统回收。

问题四:可以在子线程中 join 另一个子线程吗?

可以。任何拥有 JoinHandle 的线程都可以调用 join()。但要注意避免死锁(A 等 B,B 等 A)。

适用场景 ​

  • 等待并行任务完成:所有子任务完成后汇总结果
  • 串行化并行结果:按顺序收集并行计算的结果
  • 错误检测:检查线程是否 panic
  • 资源生命周期管理:确保线程完成后再释放资源

注意事项 ​

  • join() 消耗 JoinHandle,只能调用一次
  • join() 阻塞调用它的线程
  • 先启动所有线程再 join 才能实现并行
  • 立即 join 等于串行执行
  • 标准库没有超时 join 的功能
  • 不 join 的线程在主线程退出时被终止

总结 ​

join() 阻塞当前线程直到目标线程完成,返回 Result<T, Box<dyn Any + Send>>。它消耗 JoinHandle,只能调用一次。要实现并行效果,必须先启动所有线程,然后再逐个 join——如果启动后立即 join 就变成串行了。join 的 Err 表示线程 panic,可以用 downcast_ref 提取 panic 信息。批量线程的结果按 join 调用顺序收集。标准库不支持超时 join,需要超时功能可用通道实现。不调用 join 的线程在主线程退出时会被终止。