Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Modifying a bool variable inside a thread

I have this code :

let mut is_ok_test = false;

// SCAN COMMAND
let handle = thread::spawn(move || { 
        is_ok_test = true;
});

handle.join().unwrap();

if is_ok_test == true { println!("Success"); } else { println!("Test Failed") }

The is_ok_test variable always remains false. I don’t understand why.

When modifyng the variable inside thei get a warning like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

value assigned to `is_ok_test` is never read
maybe it is overwritten before being read?
unused variable: `is_ok_test`
did you mean to capture by reference instead?

I tried to add & but it doesn’t work.

>Solution :

The problem is that due to move || {... and booleans being Copy instead of changing the outside boolean you create a copy of it inside the closure.
That’s also what your warnings are referring to, the inner is_ok is never read.

You can share ownership between the new and the main thread by using an Arc. To get back mutabilitiy you can use an AtomicBool:

use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::Relaxed;
fn main() {
    let mut is_ok_test = Arc::new(AtomicBool::new(false));

    // SCAN COMMAND
    let handle = {
        let is_ok_test = is_ok_test.clone();
        std::thread::spawn(move || {
            is_ok_test.store(true, Relaxed);
        })
    };

    handle.join().unwrap();

    if is_ok_test.load(Relaxed) == true { println!("Success"); } else { eprintln!("Test Failed") }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading