Move object with lower lifetime to higher lifetime scope

Essentially I want to do the following


struct MyStruct<'a> {
    additional_data: u32,
    ptr: &'a i32
}

fn test() {
    let data = 52;
    let obj = MyStruct {
        additional_data: 0,
        ptr: &data 
    };
    let handle = thread::spawn(move || {
        let obj = obj;
    }); 
    
    handle.join().unwrap();
    // data gets dropped here
    // so it lives longer than the created thread
    // therefore it is safe
}

Of course this won't work because thread::spawn requires an argument that satisfy 'static lifetime bound. So my question is how can I do this move operation with unsafe code without using a Box (don't want heap allocations). I tried transmuting the obj to [u8;mem::size_of::<MyStruct>()] but I don't know if this is safe and it won't work either because generic const expressions are unstable.

The usual way to solve this exact problem is by using crossbeam::scope or rayon::scope. In the future you'll be able to replace them with std::thread::scope, when it becomes stable. The way this is done under the hood is by using std::thread::Builder::spawn_unchecked, which doesn't require 'static (but is of course unsafe).

More in general, you could transmute obj to MyStruct<'static>, but this is generally pretty dangerous since there's nothing that will catch eventual mistakes on your end.

2 Likes

Ah interesting, i didn't thought of using an unchecked spawn method. Thanks for your answer!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.