forked from t4sk/hello-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmutex.rs
More file actions
42 lines (35 loc) · 969 Bytes
/
mutex.rs
File metadata and controls
42 lines (35 loc) · 969 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#![allow(unused)]
use std::sync::{Mutex, MutexGuard};
use std::thread;
// Mutex
// - Mutual exclusion
// - Allows access to data from 1 thread at a time
fn main() {
let m: Mutex<i32> = Mutex::new(0);
{
let mut val: MutexGuard<'_, i32> = m.lock().unwrap();
println!("{:?}", m);
// Trying to acquire the second lock will block this thread
// let mut val = m.lock().unwrap();
*val += 1;
// mutex guard is dropped
}
{
let mut val = m.lock().unwrap();
*val += 1;
// mutex guard is dropped
}
println!("{:?}", m);
// Example of Mutex with scoped threads
thread::scope(|scope| {
scope.spawn(|| {
let mut val: MutexGuard<'_, i32> = m.lock().unwrap();
*val += 1;
});
scope.spawn(|| {
let mut val: MutexGuard<'_, i32> = m.lock().unwrap();
*val += 1;
});
});
println!("{:?}", m);
}