I have this code:
use std::thread;
use std::time::Duration;
struct State {
value: u32,
}
impl State{
pub fn new() -> State{
State{ value: 0 }
}
}
fn main() {
run_thread();
for i in 1..10 {
println!("hi number {i} from the main thread!");
thread::sleep(Duration::from_millis(300));
}
}
fn run_thread(){
let state = State::new();
thread::spawn(|| {
let mut state = state;
for i in 1..10 {
state.value = i;
println!("hi number {i} from the spawned thread!");
thread::sleep(Duration::from_millis(300));
}
});
}
I do not understand why it compiles.
As far as I understand it the variable state in run_thread() is allocated on the stack.
Then it is moved in the closure and since it does not implement the copy trait under the hood there will be just a pointer passed.
But when run_thread() returns the stackframe will be destroyed, but the thread will still access the memory at that location and will corrupt the stackframe of any new called function.
Is this really the case ? If not, what did I get wrong ?
thank you
Gerhard