File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -3,6 +3,7 @@ use myutils::stuff;
33use myutils:: testing;
44//use guessgame
55use paral:: channels;
6+ use paral:: mutex;
67use paral:: threads;
78
89fn main ( ) {
@@ -18,4 +19,5 @@ fn main() {
1819 intmut:: weakrefs ( ) ;
1920 threads:: demo ( ) ;
2021 channels:: demo ( ) ;
22+ mutex:: demo ( ) ;
2123}
Original file line number Diff line number Diff line change @@ -14,7 +14,7 @@ pub fn demo() {
1414 ] ;
1515 for val in vals {
1616 tx. send ( val) . unwrap ( ) ;
17- thread:: sleep ( std:: time:: Duration :: from_secs ( 1 ) ) ;
17+ thread:: sleep ( std:: time:: Duration :: from_secs_f32 ( 0. 1) ) ;
1818 }
1919 } ) ;
2020
@@ -27,7 +27,7 @@ pub fn demo() {
2727 ] ;
2828 for val in vals {
2929 tx2. send ( val) . unwrap ( ) ;
30- thread:: sleep ( std:: time:: Duration :: from_secs ( 1 ) ) ;
30+ thread:: sleep ( std:: time:: Duration :: from_secs_f32 ( 0. 1) ) ;
3131 }
3232 } ) ;
3333
Original file line number Diff line number Diff line change 11pub mod channels;
2+ pub mod mutex;
23pub mod threads;
Original file line number Diff line number Diff line change 1+ use std:: sync:: { Arc , Mutex } ;
2+ use std:: thread;
3+
4+ pub fn demo ( ) {
5+ println ! ( "Mutex" ) ;
6+ let m = Mutex :: new ( 5 ) ;
7+ {
8+ let mut num = m. lock ( ) . unwrap ( ) ;
9+ * num = 6 ;
10+ }
11+ println ! ( "m = {:?}" , m) ;
12+
13+ let counter = Arc :: new ( Mutex :: new ( 0 ) ) ;
14+ let mut handles = vec ! [ ] ;
15+ for _ in 0 ..10 {
16+ let counter = Arc :: clone ( & counter) ;
17+ let handle = thread:: spawn ( {
18+ move || {
19+ let mut num = counter. lock ( ) . unwrap ( ) ;
20+ * num += 1 ;
21+ }
22+ } ) ;
23+ handles. push ( handle) ;
24+ }
25+ for handle in handles {
26+ handle. join ( ) . unwrap ( ) ;
27+ }
28+ println ! ( "Result: {}" , * counter. lock( ) . unwrap( ) ) ;
29+ }
You can’t perform that action at this time.
0 commit comments