# HG changeset patch # User Shinji KONO # Date 1610429645 -32400 # Node ID 8768d36c3b6984e5911ff16f5def6c1809a7474a # Parent 6e7204a1ba9938226e5abce2d83a28de268c3b8e thread test diff -r 6e7204a1ba99 -r 8768d36c3b69 src/t16thread/src/lib.rs --- /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; diff -r 6e7204a1ba99 -r 8768d36c3b69 src/t16thread/src/main.rs --- 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 diff -r 6e7204a1ba99 -r 8768d36c3b69 src/t16thread/src/mpsc_test.rs --- 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 +} + diff -r 6e7204a1ba99 -r 8768d36c3b69 src/t16thread/src/racecondition.rs --- /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()); +}