State in multi thread rust application

Viewed 83

I am writing a multithread program in rust, where I need a shared object to keep track of the state of the application. Coming from a C++ background I would have solved this with a unique pointer wrapping a static object (a singleton implementation basically). In rust I am a little bit confused since static objects are very different. Looking around on the web I found the lazy_static crate, so I handled my problem in this way:

the structure that handles my state:

struct Status {
    pub enabled: bool,
    pub num_file_moved: u64,
    pub num_file_moved_err: u64,
    pub tot_size: u64,
}

the static object that contains the status of the application:

use lazy_static::lazy_static;

lazy_static! {
    static ref STATUS: Mutex<Status> = Mutex::new(Status::default());
}

And then I wrote a series of method that allows to read/write the status object, e.g.:

pub fn enabled() -> bool {
    STATUS.lock().unwrap().enabled
}

pub fn set_enable(new_val: bool) {
    STATUS.lock().unwrap().enabled = new_val;
}

Is this the correct way to handle this issue? My doubt is that I am trying to bring a C++ concept to Rust.

0 Answers
Related