I am trying to understand global static data with a mutex. It boils down to this:
use std::sync::{Mutex};
#[derive(Debug)]
struct MyStruct {
i_value: i32,
}
static mut MY_GLOBAL_MUT: Mutex<Option<MyStruct>> = Mutex::new(None);
fn main() {
for i in 0..3 {
unsafe {
let mut the_option = MY_GLOBAL_MUT.lock().expect("Cant get the lock!");
match &*the_option {
Some(_v) => {
println!("{i}: Found a value!");
}
None => {
println!("{i}: Need to create the value!");
MY_GLOBAL_MUT = Mutex::new(Some(MyStruct { i_value: 42 }));
the_option = MY_GLOBAL_MUT.lock().expect("Cant get the lock!");
}
}
println!("{i}: local_mystruct = {}", the_option.as_ref().unwrap().i_value);
}
}
}
Interesting... on the Rust Playground, this code does exactly what I want/hope. Compiling it locally, the first lock() blocks when coming around the second time.
Why? (the guard is dropped every run through the loop)