Do thread references require a static lifetime?

Although it is intuitively clear that links passed to spawned threads must have static lifetimes, I don’t understand what exactly makes the following code uncompiled:

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));
        }
    }
}

Compiling this small program gives the following error:

$ 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...

It seems to me that the variable awill go out of life c_clone, which is important in this case ...? Hope someone can help me understand what I am missing!

+1
source share
1 answer

, Arc Mutex : - . std::thread::spawn, , ; - - , a - , , ; , a , - , c_clone . 'static.

+5

All Articles