X-Git-Url: https://piware.de/gitweb/?p=learn-rust.git;a=blobdiff_plain;f=concepts%2Fsrc%2Fmain.rs;h=3e9bbbd0cd042234615d20dd563baf6278258464;hp=65fb785c838a2a966e6c1d4c5494f4751d5f0b0d;hb=6cf2fd87f634bb24ca0ab801a8ba3fbfff1ac418;hpb=cf171920f1d9768f922556b13042e3a3465483f3 diff --git a/concepts/src/main.rs b/concepts/src/main.rs index 65fb785..3e9bbbd 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,41 @@ 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 test_dyn_traits() { + let text = "I ate a salad for lunch today"; + let mut post = Post::new(); + post.add_text(text); + assert_eq!("", post.content()); + + post.request_review(); + assert_eq!("", post.content()); + + post.reject(); + assert_eq!("", post.content()); + + post.request_review(); + assert_eq!("", post.content()); + + post.approve(); + assert_eq!(text, post.content()); } fn main() { @@ -239,4 +275,5 @@ fn main() { test_closures(); test_iterators(); test_threads(); + test_dyn_traits(); }