comparison 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
comparison
equal deleted inserted replaced
8:2c6285996268 9:aaba40049c28
1 // #![deny(missing_docs)] 1 // #![deny(missing_docs)]
2 use std::sync::{Arc, Mutex}; 2 use std::sync::{Arc, Mutex};
3 use std::thread; 3 use std::thread;
4 use std::borrow::BorrowMut;
5
4 6
5 pub fn mainr() { 7 pub fn mainr() {
6 let counter = Arc::new(Mutex::new(0)); 8 let counter = Arc::new(Mutex::new(0));
7 let mut handles = vec![]; 9 let mut handles = vec![];
8 10
9 for _ in 0..10 { 11 for _ in 0..10 {
10 let counter = Arc::clone(&counter); 12 let counter = Arc::clone(&counter);
11 let handle = thread::spawn(move || { 13 let handle = thread::spawn(move || {
12 let mut num = counter.lock().unwrap(); 14 let mut num = counter.lock().unwrap();
13
14 *num += 1; 15 *num += 1;
15 }); 16 });
16 handles.push(handle); 17 handles.push(handle);
17 } 18 }
18 19
20 handle.join().unwrap(); 21 handle.join().unwrap();
21 } 22 }
22 23
23 println!("Result: {}", *counter.lock().unwrap()); 24 println!("Result: {}", *counter.lock().unwrap());
24 } 25 }
26
27 struct Data {
28 d : u32,
29 }
30
31 impl Data {
32 fn work(&mut self) {
33 self.d += 1;
34 }
35 }
36
37 static mut d1 : Data = Data { d : 0 };
38
39 pub fn mainu() {
40 let mut handles = vec![];
41
42 for _ in 0..10 {
43 let handle = thread::spawn(move || {
44 unsafe {
45 d1.work();
46 }
47 });
48 handles.push(handle);
49 }
50
51 for handle in handles {
52 handle.join().unwrap();
53 }
54 unsafe {
55 println!("Result: {} ", d1.d);
56 }
57 }