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;

    for handle in handles {

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

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


Here's one way:

            let before = *counter.lock().unwrap();
            *counter.lock().unwrap() = before + 1;


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.