Skip to content

Commit c48604e

Browse files
committed
use MPSC channels. Use Arc + Mutex to achieve multiple owernship and interior mutability.
1 parent 000b689 commit c48604e

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

c16_concurrency/src/main.rs

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
use std::thread;
22
use std::time::Duration;
3+
use std::sync::Arc;
4+
use std::sync::mpsc;
5+
use std::sync::Mutex;
36

47
fn main() {
58

@@ -24,4 +27,70 @@ fn main() {
2427

2528
handler1.join().unwrap();
2629

30+
let (tx, rx) = mpsc::channel();
31+
32+
let tx1 = tx.clone();
33+
thread::spawn(move || {
34+
let val = String::from("t1: hi");
35+
tx1.send(val).unwrap();
36+
tx1.send(3.to_string()).unwrap();
37+
38+
let vals = vec![
39+
String::from("t1: hi"),
40+
String::from("t1: from"),
41+
String::from("t1: the"),
42+
String::from("t1: thread"),
43+
];
44+
45+
for val in vals {
46+
tx1.send(val).unwrap();
47+
thread::sleep(Duration::from_secs(1));
48+
}
49+
});
50+
51+
thread::spawn(move || {
52+
let vals = vec![
53+
String::from("t2: more"),
54+
String::from("t2: messages"),
55+
String::from("t2: for"),
56+
String::from("t2: you"),
57+
];
58+
59+
for val in vals {
60+
tx.send(val).unwrap();
61+
thread::sleep(Duration::from_secs(1));
62+
}
63+
});
64+
65+
let received = rx.recv().unwrap();
66+
println!("Got: {}", received);
67+
println!("Got: {}", rx.recv().unwrap());
68+
//println!("Got: {}", rx.recv().unwrap()); //unwrap() will fail due to an empty result.
69+
70+
71+
for received in rx {
72+
println!("Got: {}", received);
73+
}
74+
75+
76+
let counter = Arc::new(Mutex::new(0));
77+
let mut handles = vec![];
78+
79+
for _ in 0..10 {
80+
// increase counter by 1 in each thread
81+
let counter = Arc::clone(&counter);
82+
let handle = thread::spawn(move || {
83+
let mut num = counter.lock().unwrap();
84+
85+
*num += 1;
86+
});
87+
handles.push(handle);
88+
}
89+
90+
for handle in handles {
91+
handle.join().unwrap();
92+
}
93+
94+
println!("Final counter result: {}", *counter.lock().unwrap());
95+
2796
}

0 commit comments

Comments
 (0)