How To Share Mutable Static Data Between Threads/Functions in Rust

Hi everyone, good day to you!

I know there are thousands of question just like this one, but those answers I found from other post, stackoverflow, reddit..., do not satisfy me. Because I don't understand (as I am too new to Rust) or just simply the answer doesn't work or match my scenario.

This is the thing I want:

//DECLARE MUT STATIC VARIABLE X = DATETIME, OBJECT, STRING, INT...;
//The problem is I need X to be anything, not just string and int.

fn main() {
    
    THIS_PART_OF_CODE_LOAD_X_FROM_FILE_OR_DATBSE();

    let updateJob = thread::spawn(|| {THIS_FUNCTION_UPDATE_X_CONTINOUSLY()});

    let displayJob = thread::spawn(|| {THIS_FUNCTION_SHOW_X_CONTINOUSLY()});

}

fn THIS_PART_OF_CODE_LOAD_X_FROM_FILE_OR_DATBSE() { //INITIALIZED

    //X = 29;    
}


fn THIS_FUNCTION_UPDATE_X_CONTINOUSLY() { //UPDATE
    
    loop {
        //X++;
        //thread::sleep(1sec);
    }
}

fn THIS_FUNCTION_SHOW_X_CONTINOUSLY() { //DISPLAY/RENDER

    loop {
        //println!("{}", X);
        //thread::sleep(800ms);
    }
}

fn THIS_FUNCTION_UPDATE_X_SOMETIME() { //(^_-)
    
    loop {
        //X++;
        //thread::sleep(1week);
    }
}

But as I tried, read and then re-tried, Rust does not let me do this :smiling_face_with_tear:.

  1. Static mut can not be datetime, object, just int and string are allowed.
  2. I tried lazy_static and something else, only one thread can access to the variable. (Or I did it wrong, please just show me how or a link to proper informations).
  3. Is the application designed like the code I show above a disaster? Am I wrong/totally don't understand something and is there any better way to do it, without static global variables?
  4. In case it's do-able, would you mind please show me tut-link/document or code to that... Thank you :smiling_face_with_tear:!

Updating a single memory location from multiple threads is incredibly dangerous, which is why it's not straightforward to do the simple way in Rust.

You need to use a type that can synchronize accesses to the value, like a Mutex or RwLock

1 Like

Just don't use static mut. Don't use static x: Mutex<T> either unless you really need that. Most of time, you don't.

Instead, create X and wrap it in an Arc<Mutex<X>>, then clone the Arc into threads.

1 Like

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.