From ef64ba88ab124cc217c7d437da8ad3af4be8b583 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Tue, 5 Feb 2019 14:19:29 -0500 Subject: [PATCH] Add mutex example --- .idea/misc.xml | 1 + .idea/rust.iml | 5 +++++ .idea/workspace.xml | 46 ++++++++++++++++++++++++++------------------- mutex/Cargo.toml | 7 +++++++ mutex/src/main.rs | 40 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 80 insertions(+), 19 deletions(-) create mode 100644 mutex/Cargo.toml create mode 100644 mutex/src/main.rs diff --git a/.idea/misc.xml b/.idea/misc.xml index 1c9acf9..76830ba 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -29,6 +29,7 @@ + diff --git a/.idea/rust.iml b/.idea/rust.iml index 971bd3a..0650e07 100644 --- a/.idea/rust.iml +++ b/.idea/rust.iml @@ -118,6 +118,10 @@ + + + + @@ -136,6 +140,7 @@ + diff --git a/.idea/workspace.xml b/.idea/workspace.xml index bdb3b8d..1826468 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -15,10 +15,10 @@ - + - - + + @@ -96,6 +96,7 @@ @@ -129,12 +130,12 @@ - + - + @@ -168,7 +169,7 @@ - + @@ -196,7 +197,7 @@ - + + + - - + - @@ -765,7 +766,14 @@ - + + + + + + + + diff --git a/mutex/Cargo.toml b/mutex/Cargo.toml new file mode 100644 index 0000000..c6b3678 --- /dev/null +++ b/mutex/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "mutex" +version = "0.1.0" +authors = ["Timothy Warren "] +edition = "2018" + +[dependencies] diff --git a/mutex/src/main.rs b/mutex/src/main.rs new file mode 100644 index 0000000..399ba50 --- /dev/null +++ b/mutex/src/main.rs @@ -0,0 +1,40 @@ +use std::sync::{Arc, Mutex}; // Rc is not thread safe, but Arc is. (Atomic Reference Count) +use std::thread; + +fn single_thread_example() { + let m = Mutex::new(5); + + { + let mut num = m.lock().unwrap(); + *num = 6; + } // Reference to mutex value goes out of scope, lock is released + + println!("m = {:?}", m); +} + +fn multi_thread_example() { + 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()); +} + +fn main() { + single_thread_example(); + + multi_thread_example(); +}