2

first:

use std::thread;
use std::sync::Arc;
use std::sync::Mutex;
#[derive(Debug)]
struct MyBox(*const u8);
unsafe impl Send for MyBox {}
unsafe impl Sync for MyBox {}

fn main() {
    let b = &MyBox(5 as *const u8);
    let v = Arc::new(Mutex::new(b));
    let t = thread::spawn(move || {
        let _v1 =  v.lock().unwrap();
    });
    t.join().unwrap();
}

second:

use std::thread;
use std::sync::Arc;
use std::sync::Mutex;
#[derive(Debug)]
struct MyBox(*const u8);
unsafe impl Send for MyBox {}
unsafe impl Sync for MyBox {}

fn main() {
    let b = MyBox(5 as *const u8);
    let v = Arc::new(Mutex::new(&b));
    let t = thread::spawn(move || {
        let _v1 =  v.lock().unwrap();
    });
    t.join().unwrap();
}

first will be .but second :b does not live long enough borrowed value does not live long enough what's wrong here? They are both MyBox reference.

  • Your explanation seems disjointed. Did you inadvertently drop and/or repeat some words in "first will be .but second :b does not live long enough borrowed value does not live long enough"? – ShadowRanger May 31 '23 at 02:25

1 Answers1

1

The expression MyBox(5 as *const u8) is made up of only constants (and a few other criteria) and thus can be const promoted. So when you create b as a reference, the value can actually be put in static storage and so b is a &'static MyBox.

In the second case, when b is not a reference, it won't use static storage since b is unarguably a local variable and thus has function-local storage. So a reference to that value cannot satisfy the 'static lifetime that thread::spawn requires.

As a side note, you should use thread::scope when you want to create threads that can reference local variables.

kmdreko
  • 42,554
  • 6
  • 57
  • 106
  • 1
    The actual error message thrown for the second code is completely unrelated to the `'static` requirement of `thread::spawn()`. The code won't compile even if you remove all mentions of `thread`. The borrow `&b` only lives until the end of the statement, so it can't be moved into a `Mutex` that lives longer than that. – Sven Marnach May 31 '23 at 08:26