1
1
use std:: thread;
2
2
use std:: time:: Duration ;
3
+ use std:: sync:: Arc ;
4
+ use std:: sync:: mpsc;
5
+ use std:: sync:: Mutex ;
3
6
4
7
fn main ( ) {
5
8
@@ -24,4 +27,70 @@ fn main() {
24
27
25
28
handler1. join ( ) . unwrap ( ) ;
26
29
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
+
27
96
}
0 commit comments