view src/t16thread/src/racecondition.rs @ 9:aaba40049c28

unsafe race condition
author Shinji KONO <kono@ie.u-ryukyu.ac.jp>
date Tue, 12 Jan 2021 15:47:17 +0900
parents 2c6285996268
children
line wrap: on
line source

// #![deny(missing_docs)]
use std::sync::{Arc, Mutex};
use std::thread;
use std::borrow::BorrowMut;


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

    for _ in 0..10 {
        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());
}

struct Data {
    d : u32,
}

impl Data {
    fn work(&mut self) {
        self.d += 1;
    }
}

static mut d1 : Data = Data { d : 0 };

pub fn mainu() {
    let mut handles = vec![];

    for _ in 0..10 {
        let handle = thread::spawn(move || {
            unsafe {
                d1.work();
            }
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }
    unsafe {
        println!("Result: {} ", d1.d);
    }
}