线程引用需要静态生存期?

Mok*_*sha 1 multithreading lifetime rust

虽然直觉上传递给生成的线程的引用需要具有静态生命周期,但我不清楚究竟是什么使得以下代码无法编译:

use std::sync::Arc;
use std::sync::Mutex;

struct M;

fn do_something(m : Arc<Mutex<&M>>) {
    println!("Ha, do nothing!");
}

fn main() {
    let a = M;
    {
        let c : Arc<Mutex<&M>> = Arc::new(Mutex::new(&a));
        for i in 0..2 {
            let c_clone = c.clone();
            ::std::thread::spawn(move || do_something(c_clone));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

编译这个小程序会出现以下错误:

$ rustc -o test test.rs
test.rs:13:55: 13:56 error: `a` does not live long enough
test.rs:13         let c : Arc<Mutex<&M>> = Arc::new(Mutex::new(&a));
                                                             ^
note: reference must be valid for the static lifetime...
Run Code Online (Sandbox Code Playgroud)

在我看来,变量a将会超出现实c_clone,这在这种情况下是重要的......?希望有人能帮助我理解我所缺少的东西!

Chr*_*gan 5

在本质上,ArcMutex包装是多余的:你是传递一个参考的东西在本地堆栈.当你生成一个线程时std::thread::spawn,没有什么可以将生命周期联系在一起; 主线程完全可以自由地结束并释放其中的任何内容 - 在这种情况下,包括 - 在a它产生的任何其他线程之前甚至开始执行; 因此,在这种情况下,a可以在生成的线程做任何事情时引用释放的内存,留下c_clone作为悬空指针.这就是生成线程关闭环境必须的原因'static.