changeset 7:8768d36c3b69

thread test
author Shinji KONO <kono@ie.u-ryukyu.ac.jp>
date Tue, 12 Jan 2021 14:34:05 +0900
parents 6e7204a1ba99
children 2c6285996268
files src/t16thread/src/lib.rs src/t16thread/src/main.rs src/t16thread/src/mpsc_test.rs src/t16thread/src/racecondition.rs
diffstat 4 files changed, 53 insertions(+), 6 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/t16thread/src/lib.rs	Tue Jan 12 14:34:05 2021 +0900
@@ -0,0 +1,7 @@
+/*!
+  t16 thread
+*/
+
+#![deny(missing_docs)]
+
+mod racecondition;
--- a/src/t16thread/src/main.rs	Tue Jan 12 12:02:17 2021 +0900
+++ b/src/t16thread/src/main.rs	Tue Jan 12 14:34:05 2021 +0900
@@ -1,9 +1,23 @@
+mod mpsc_test;
+// use racecondition;
+use racecondition::mainc;
+
 use std::thread;
 use std::time::Duration;
 
+fn main1() {
+    let v = vec![1, 2, 3];
+
+    let handle = thread::spawn(move || {
+        println!("Here's a vector: {:?}", v);
+    });
+    // drop(v);
+    handle.join().unwrap();
+}
+
 fn main() {
-    thread::spawn(|| {
-        for i in 1..10 {
+    let handle = thread::spawn(|| {
+        for i in 0..10 {
             println!("hi number {} from the spawned thread!", i);
             thread::sleep(Duration::from_millis(1));
         }
@@ -13,4 +27,9 @@
         println!("hi number {} from the main thread!", i);
         thread::sleep(Duration::from_millis(1));
     }
+    handle.join().unwrap();  // without this, some data are dropped
+    // main1();
+    // mpsc_test::main_mpsc();
+    // mpsc_test::mainc();
+    racecondition::mainr();
 }
\ No newline at end of file
--- a/src/t16thread/src/mpsc_test.rs	Tue Jan 12 12:02:17 2021 +0900
+++ b/src/t16thread/src/mpsc_test.rs	Tue Jan 12 14:34:05 2021 +0900
@@ -1,8 +1,8 @@
-use std::sync::mpsc;
-use std::thread;
-use std::time::Duration;
 
 pub mod mpsc_test {
+    use std::sync::mpsc;
+    use std::thread;
+    use std::time::Duration;
     pub fn main_mpsc() {
         let (tx, rx) = mpsc::channel();
 
@@ -61,4 +61,5 @@
             println!("Got: {}", received);
         }
     }
-}
\ No newline at end of file
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/t16thread/src/racecondition.rs	Tue Jan 12 14:34:05 2021 +0900
@@ -0,0 +1,20 @@
+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());
+}