study_example/concurrency/
message_thread.rs1use std::sync::mpsc;
2use std::thread;
4use std::time::Duration;
5
6fn channel_test() {
11 let (tx, rx) = mpsc::channel();
12 thread::spawn(move || {
13 let val = String::from("other thread send hi.");
14 tx.send(val).unwrap();
15 });
18 let received = rx.recv().unwrap();
19 println!("main thread got: {received}");
20}
21
22fn send_multi_val_in_channel() {
30 let (tx, rx) = mpsc::channel();
31 thread::spawn(move || {
32 let vals = vec![
33 String::from("other thread val 1"),
34 String::from("other thread val 2"),
35 String::from("other thread val 3"),
36 String::from("other thread val 4"),
37 ];
38 for val in vals {
39 tx.send(val).unwrap();
40 thread::sleep(Duration::from_secs(1));
41 }
42 });
43
44 for receives in rx {
45 println!("main thread got: {}", receives);
46 }
47}
48
49fn multi_producer_clone_test() {
62 let (tx, rx) = mpsc::channel();
63 let tx1 = tx.clone();
64 thread::spawn(move || {
65 let vals = vec![
66 String::from("other thread val 1"),
67 String::from("other thread val 2"),
68 String::from("other thread val 3"),
69 String::from("other thread val 4"),
70 ];
71 for val in vals {
72 tx1.send(val + "send from tx1").unwrap();
73 thread::sleep(Duration::from_secs(1));
74 }
75 });
76 let tx2 = tx.clone();
77 thread::spawn(move || {
78 let vals = vec![
79 String::from("other thread val 1"),
80 String::from("other thread val 2"),
81 String::from("other thread val 3"),
82 String::from("other thread val 4"),
83 ];
84 for val in vals {
85 tx2.send(val + "send from tx2").unwrap();
86 thread::sleep(Duration::from_secs(1));
87 }
88 });
89 thread::spawn(move || {
91 tx.send(String::from("send from tx other thread.")).unwrap();
92 });
93 for receives in rx {
94 println!("main thread Got val: {}", receives);
95 }
96}
97
98pub fn messsage_thread_study() {
99 channel_test();
100 send_multi_val_in_channel();
101 multi_producer_clone_test();
102}