Write Incorrect Threading Code?

Following code is using Mutex to make sure the counter counting correctly.

Just for curiosity, how in Rust can I write it (maybe without Mutex or what ever) using the same (100 or any number) of threads to demonstrate the insistency of threading programming without locks (to demo the counter counting incorrectly)?

use std::sync::{Mutex, Arc};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..100 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();

            *num += 1;
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Result: {}", *counter.lock().unwrap());
}

static mut is a terrible candidate: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=1bd9abf3ed1afa51504071e33c250422

2 Likes

Here's one way:

            let before = *counter.lock().unwrap();
            thread::sleep(Duration::from_millis(100));
            *counter.lock().unwrap() = before + 1;

https://play.rust-lang.org/?version=stable&mode=release&edition=2018&gist=56b4c5a8c89a887f0eb8c632d705db17

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.