From: Martin Pitt Date: Sun, 29 Aug 2021 08:15:43 +0000 (+0200) Subject: concepts: Shared memory and mutex between threads X-Git-Url: https://piware.de/gitweb/?a=commitdiff_plain;h=89ba5f70f2de2cf038b2abb701a3d257c6b965d8;p=learn-rust.git concepts: Shared memory and mutex between threads --- diff --git a/concepts/src/main.rs b/concepts/src/main.rs index 65fb785..94bdb96 100644 --- a/concepts/src/main.rs +++ b/concepts/src/main.rs @@ -205,6 +205,7 @@ fn test_threads() { t1.join().unwrap(); + // message passing let (tx1, rx) = sync::mpsc::channel(); let tx2 = tx1.clone(); @@ -228,6 +229,22 @@ fn test_threads() { sender1.join().unwrap(); sender2.join().unwrap(); + + // shared state + let counter = sync::Arc::new(sync::Mutex::new(0)); + let mut threads = vec![]; + for _ in 0..10 { + let tc = sync::Arc::clone(&counter); + threads.push(thread::spawn(move || { + *tc.lock().unwrap() += 1; + })); + } + + for t in threads { + t.join().unwrap(); + } + + println!("counter: {}", *counter.lock().unwrap()); } fn main() {