changeset 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 7eb649571bc6
files src/t16thread/src/main.rs src/t16thread/src/racecondition.rs
diffstat 2 files changed, 38 insertions(+), 4 deletions(-) [+]
line wrap: on
line diff
--- a/src/t16thread/src/main.rs	Tue Jan 12 14:56:07 2021 +0900
+++ b/src/t16thread/src/main.rs	Tue Jan 12 15:47:17 2021 +0900
@@ -29,7 +29,8 @@
     }
     handle.join().unwrap();  // without this, some data are dropped
     // main1();
-    t16thread::mpsc_test::mainm();
-    t16thread::mpsc_test::mainc();
-    t16thread::racecondition::mainr();
+    // t16thread::mpsc_test::mainm();
+    // t16thread::mpsc_test::mainc();
+    // t16thread::racecondition::mainr();
+    t16thread::racecondition::mainu();
 }
\ No newline at end of file
--- a/src/t16thread/src/racecondition.rs	Tue Jan 12 14:56:07 2021 +0900
+++ b/src/t16thread/src/racecondition.rs	Tue Jan 12 15:47:17 2021 +0900
@@ -1,6 +1,8 @@
 // #![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));
@@ -10,7 +12,6 @@
         let counter = Arc::clone(&counter);
         let handle = thread::spawn(move || {
             let mut num = counter.lock().unwrap();
-
             *num += 1;
         });
         handles.push(handle);
@@ -22,3 +23,35 @@
 
     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);
+    }
+}