view src/t16thread/src/racecondition.rs @ 7:8768d36c3b69

thread test
author Shinji KONO <kono@ie.u-ryukyu.ac.jp>
date Tue, 12 Jan 2021 14:34:05 +0900
parents
children 2c6285996268
line wrap: on
line source

use std::sync::Mutex;
use std::thread;
pub fn mainr() {
    let counter = Mutex::new(0);
    let mut handles = vec![];
    for _ in 0..10 {
        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());
}