move 闭包与线程 ​

核心概念 ​

thread::spawn 要求闭包满足 'static 生命周期,这意味着闭包不能借用创建线程的函数中的局部变量——因为线程可能比那个函数活得更久,引用就变成了悬垂引用。move 关键字将被引用的变量的所有权转移到闭包中,让闭包拥有数据而不是借用数据,从而满足 'static 约束。在实际的线程编程中,几乎所有传给 thread::spawn 的闭包都需要 move。

rust
use std::thread;

fn main() {
    let name = String::from("Rust");
    let count = 5;

    // 没有 move:编译错误
    // thread::spawn(|| {
    //     println!("{} {}", name, count);  // 借用了 name 和 count
    // });  // 错误:闭包可能比 name 活得更久

    // 有 move:编译通过
    let handle = thread::spawn(move || {
        // name 和 count 的所有权被移入闭包
        for i in 0..count {
            println!("[{}] 第 {} 次", name, i + 1);
        }
    });

    // name 已被移走,不能再使用
    // println!("{}", name);  // 编译错误

    // count 是 Copy 类型,被复制进闭包,原始值仍可用
    println!("count 仍然可用: {}", count);

    handle.join().unwrap();
}

move 对不同类型的影响 ​

rust
use std::thread;

fn main() {
    // === Copy 类型:复制进闭包 ===
    let x = 42;         // i32 是 Copy
    let pi = 3.14;      // f64 是 Copy
    let flag = true;    // bool 是 Copy

    let handle = thread::spawn(move || {
        println!("x={}, pi={}, flag={}", x, pi, flag);
    });
    handle.join().unwrap();

    // Copy 类型在 move 后仍然可以在外面用
    println!("外部: x={}, pi={}, flag={}", x, pi, flag);

    // === 非 Copy 类型:移走所有权 ===
    let s = String::from("hello");
    let v = vec![1, 2, 3];

    let handle = thread::spawn(move || {
        println!("s={}, v={:?}", s, v);
    });
    handle.join().unwrap();

    // 非 Copy 类型在 move 后不能再使用
    // println!("{}", s);  // 编译错误
    // println!("{:?}", v);  // 编译错误

    // === 需要在主线程和子线程中都使用数据 ===
    let data = String::from("共享数据");

    // 方法1:先 clone 再 move
    let data_for_thread = data.clone();
    let handle = thread::spawn(move || {
        println!("线程: {}", data_for_thread);
    });
    println!("主线程: {}", data);  // 用原始值
    handle.join().unwrap();
}

多个线程共享数据 ​

rust
use std::thread;
use std::sync::Arc;

fn main() {
    // 错误做法:每个线程都 move 同一个变量
    // let data = vec![1, 2, 3];
    // let h1 = thread::spawn(move || println!("{:?}", data));
    // let h2 = thread::spawn(move || println!("{:?}", data));  // 编译错误:data 已被移走

    // 方法1:clone
    let data = vec![1, 2, 3];
    let data_clone = data.clone();
    let h1 = thread::spawn(move || println!("线程1: {:?}", data));
    let h2 = thread::spawn(move || println!("线程2: {:?}", data_clone));
    h1.join().unwrap();
    h2.join().unwrap();

    // 方法2:Arc(更高效,共享同一份数据)
    let shared = Arc::new(vec![10, 20, 30, 40, 50]);

    let mut handles = Vec::new();
    for i in 0..3 {
        let data = Arc::clone(&shared);  // 增加引用计数
        handles.push(thread::spawn(move || {
            println!("线程{}: {:?}, 总和={}", i, data, data.iter().sum::<i32>());
        }));
    }

    for h in handles {
        h.join().unwrap();
    }

    // 主线程仍可以使用 shared
    println!("主线程: {:?}", shared);
}

move 闭包中的部分 move ​

rust
use std::thread;

fn main() {
    let name = String::from("张三");
    let age = 25;
    let city = String::from("北京");

    // move 会移走所有被使用的变量
    let handle = thread::spawn(move || {
        // name, age, city 都被 move 进来
        println!("{}, {}岁, {}", name, age, city);
    });
    handle.join().unwrap();

    // 如果只想移走部分变量,先把不需要移走的 clone
    let name = String::from("李四");
    let age = 30;
    let city = String::from("上海");

    let name_for_thread = name.clone();
    // city 不传给线程
    let handle = thread::spawn(move || {
        println!("{}, {}岁", name_for_thread, age);
    });

    // name 和 city 仍可用
    println!("主线程: {} 在 {}", name, city);
    handle.join().unwrap();
}

move 与循环中的线程创建 ​

rust
use std::thread;

fn main() {
    // 循环中创建线程:每次迭代的 i 会被 move 复制进闭包
    let mut handles = Vec::new();

    for i in 0..5 {
        // i 是 Copy 类型,每次循环 move 的是当前 i 的副本
        let handle = thread::spawn(move || {
            println!("线程 {}: i 的值是 {}", i, i);
            i * i
        });
        handles.push(handle);
    }

    let results: Vec<i32> = handles.into_iter()
        .map(|h| h.join().unwrap())
        .collect();
    println!("结果: {:?}", results);

    // 循环中 move 非 Copy 类型
    let names = vec!["Alice", "Bob", "Charlie", "David", "Eve"];
    let mut handles = Vec::new();

    for name in names {
        // name 是 &str(Copy),直接 move
        handles.push(thread::spawn(move || {
            format!("Hello, {}!", name)
        }));
    }

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

    // 如果需要用 String
    let data = vec![
        String::from("任务A"),
        String::from("任务B"),
        String::from("任务C"),
    ];

    let handles: Vec<_> = data.into_iter()
        .enumerate()
        .map(|(i, task)| {
            // into_iter 已经给出所有权,不需要额外 clone
            thread::spawn(move || {
                format!("线程{}: 处理 {}", i, task)
            })
        })
        .collect();

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

基本示例 ​

用 move 闭包实现并行单词统计:

rust
use std::thread;
use std::collections::HashMap;

fn count_words(text: &str) -> HashMap<String, usize> {
    let mut map = HashMap::new();
    for word in text.split_whitespace() {
        let word = word.to_lowercase();
        let word = word.trim_matches(|c: char| !c.is_alphanumeric());
        if !word.is_empty() {
            *map.entry(word.to_string()).or_insert(0) += 1;
        }
    }
    map
}

fn merge_counts(mut a: HashMap<String, usize>, b: HashMap<String, usize>) -> HashMap<String, usize> {
    for (word, count) in b {
        *a.entry(word).or_insert(0) += count;
    }
    a
}

fn main() {
    let texts = vec![
        "the quick brown fox jumps over the lazy dog the fox",
        "rust is a systems programming language rust is fast",
        "the rust programming language is safe and fast",
        "quick brown fox and lazy dog are in the story the end",
    ];

    // 每个文本块在独立线程中统计
    let handles: Vec<_> = texts.into_iter()
        .enumerate()
        .map(|(i, text)| {
            let text_owned = text.to_string();  // 获取所有权
            thread::spawn(move || {
                println!("线程{}: 统计 '{}...'", i, &text_owned[..20.min(text_owned.len())]);
                count_words(&text_owned)
            })
        })
        .collect();

    // 收集并合并结果
    let mut total_counts = HashMap::new();
    for handle in handles {
        let partial = handle.join().unwrap();
        total_counts = merge_counts(total_counts, partial);
    }

    // 按频率排序输出
    let mut sorted: Vec<_> = total_counts.into_iter().collect();
    sorted.sort_by(|a, b| b.1.cmp(&a.1));

    println!("\n=== 词频统计 ===");
    for (word, count) in sorted.iter().take(15) {
        let bar = "#".repeat(*count);
        println!("  {:>12}: {} ({})", word, bar, count);
    }
    println!("共 {} 个不同的单词", sorted.len());
}

常见问题 ​

问题一:为什么线程的闭包几乎总是需要 move?

thread::spawn 要求 'static,这意味着闭包不能借用局部变量。move 将变量所有权转移到闭包中,使闭包不依赖任何外部引用,满足 'static 约束。

问题二:move 后主线程还能用那个变量吗?

Copy 类型(i32、f64、bool 等)被复制进闭包,原始值仍可用。非 Copy 类型(String、Vec 等)被移走,原始变量不可用。如果需要在两边都使用,先 clone 或用 Arc。

问题三:move 闭包和 FnOnce 的关系是什么?

move 决定如何捕获变量(按值),闭包的 trait 类型(Fn/FnMut/FnOnce)取决于闭包体内如何使用变量。thread::spawn 要求 FnOnce(闭包只被执行一次)。

问题四:用了 move 还能在闭包中借用外部数据吗?

move 会把闭包中用到的所有外部变量都移入或复制进去。如果需要借用,可以在 move 之前创建引用的克隆,或者使用 Arc 共享数据。

适用场景 ​

  • 线程间数据传递:将数据移入新线程
  • 并行计算:每个线程处理独立的数据块
  • 后台任务:将任务需要的上下文移入后台线程
  • 跨线程共享:配合 Arc 共享只读数据

注意事项 ​

  • 线程闭包几乎总是需要 move
  • Copy 类型被复制,非 Copy 类型被移走
  • 多个线程共享数据用 Arc(只读)或 Arc<Mutex>(可变)
  • 循环中创建线程时注意每次迭代的 move 行为
  • into_iter() 已给出所有权,不需要额外 clone
  • move 只影响捕获方式,不影响闭包的 Fn trait 类型

总结 ​

move 关键字将变量所有权转移到闭包中,是线程编程的必需品。thread::spawn 要求 'static,闭包不能借用局部变量,move 通过转移所有权来满足这个约束。Copy 类型(i32 等)被复制进闭包,原始值仍可用;非 Copy 类型(String、Vec 等)被移走,原始变量不可用。多个线程共享同一份数据用 Arc::clone,每个线程获得引用计数的副本。循环中创建线程时,move 复制/移走每次迭代的变量副本。在实际并发代码中,move 闭包配合 Arc 是最常见的数据共享模式。