Skip to content

Commit 104f67a

Browse files
committed
mutex
1 parent 5b2675e commit 104f67a

4 files changed

Lines changed: 34 additions & 2 deletions

File tree

course/src/main.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use myutils::stuff;
33
use myutils::testing;
44
//use guessgame
55
use paral::channels;
6+
use paral::mutex;
67
use paral::threads;
78

89
fn main() {
@@ -18,4 +19,5 @@ fn main() {
1819
intmut::weakrefs();
1920
threads::demo();
2021
channels::demo();
22+
mutex::demo();
2123
}

paral/src/channels.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff 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

paral/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
pub mod channels;
2+
pub mod mutex;
23
pub mod threads;

paral/src/mutex.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
}

0 commit comments

Comments
 (0)