rust thread spawn 静态生命周期

通过 thread::spawn 产生的线程理论上可以比其父线程寿命更长。 如果子线程可以引用来自父线程的数据,那么当父线程停止时,这些引用将dangle(悬空, 也就是be invalid 无效)。 这就是为什么 thread::spawn 的闭包有个“static bound”。你在主函数中用join来等待线程的结束, 因此 主函数 肯定比 子进程活的时间长, 但是 编译器没办法理解这一点。

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


fn do_task(host: &str) {
    println!("{}", host)
}

fn start(hostz: &'static str) {
//fn start(hostz: &str) {
    thread::spawn(move || do_task(hostz));
}

fn main() {
    let hostx = "tw.com";

    start(hostx);

    thread::sleep(Duration::from_millis(2000));
}

如果hostz不标记为static生命周期就会报错
hostz有一个匿名的生命周期 `_ 有被 move到 lamda函数里, thread::spawn又要求static生命周期

解释:
闭包 捕获了一个 str, 所以它的上下文(环境)生命周期 不会比这个str更长, 但是 spawn又要求 闭包有static 生命周期

另外一种解决方法是:

fn start(hostz: &str) {
    let hostff = hostz.to_owned();
    thread::spawn(move || do_task(&hostff));
}

在spawn之前, 复制一份str

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注