-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patharc-mutex.rs
More file actions
173 lines (155 loc) · 5.34 KB
/
Copy patharc-mutex.rs
File metadata and controls
173 lines (155 loc) · 5.34 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
/**
* # Mutex
* Mutex ( MUTual EXclusion ) is a synchronization primitive that allows multiple
* threads to access a shared resource safely.
*
* Think mutex as a rented bike which can be used by multiple users, however,
* one should first reserve before being able to ride. The second user will be
* able to ride the bike only once the first user returns it to the owner.
*
* In case of mutex, a thread must lock the resource to be able to mutate it.
* after its operation is completed, the thread releases the lock and the next
* thread in the queue will be able to use it.
*
* when we lock a mutex, it returns a smart pointer to the resource called a
* MutexGuard which is a smart pointer that releases the lock when it goes out
* of scope.
*/
struct Rent {
user: String,
time: usize,
}
struct Bike {
ride_time: usize,
}
impl Bike {
fn new() -> Self {
Self { ride_time: 0 }
}
fn ride(&mut self, time: usize) {
println!("A {} hours bike ride has been started", time);
thread::sleep(Duration::from_secs(time as u64));
self.ride_time += time;
println!("ride complete!!");
}
}
impl Rent {
fn new(user: &str, time: usize) -> Self {
Self {
user: user.to_owned(),
time,
}
}
}
fn main() {
// in this example, a bike will be rented by 4 different people, however
// it is not possible to ride a bike by all at once, so mutex guard will
// make sure that the bike is mutated by only one user.
//
println!("\n{}", "=".repeat(50));
let bike = Arc::new(Mutex::new(Bike::new()));
let rentals = vec![
Rent::new("Alice", 5),
Rent::new("Bob", 2),
Rent::new("Charlie", 4),
Rent::new("Daniel", 3),
];
// we keep track of thread handles here
let mut handles = vec![];
// iterate through rentals
for rent in rentals {
// clone for each thread
let bike = Arc::clone(&bike);
// create a thread handle
// here we need to have the ownership of the bike to be able to mutate
// so we need to use move along with closure
let handle = thread::spawn(move || {
// since the process is threaded, waiting order might
// differ on each execution.
println!("[{:^20}] waiting!!", &rent.user.clone());
let mut rental = bike.lock().unwrap();
println!("{}", "-".repeat(50));
println!(
"The bike is now rented by {} for {} hours.",
&rent.user.clone(),
&rent.time
);
// the ride() method emulated bike ride and makes the thread sleep
// for the given time in seconds. Until the thread is completed,
// another thread will not be able to lock the bike so it will wait
// until previous thread is released.
rental.ride(rent.time);
println!("The bike ran {} hours.", rental.ride_time);
println!("[ The bike has been returned ]")
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("{}", "=".repeat(50));
println!(
"The bike had a total ride of {} hours",
bike.as_ref().lock().unwrap().ride_time
);
}
// Output (order might differ) due to threading
// ==================================================
// [ Alice ] waiting!!
// --------------------------------------------------
// The bike is now rented by Alice for 5 hours.
// [ Charlie ] waiting!!
// [ Daniel ] waiting!!
// A 5 hours bike ride has been started
// [ Bob ] waiting!!
// ride complete!!
// The bike ran 5 hours.
// [ The bike has been returned ]
// --------------------------------------------------
// The bike is now rented by Charlie for 4 hours.
// A 4 hours bike ride has been started
// ride complete!!
// The bike ran 9 hours.
// [ The bike has been returned ]
// --------------------------------------------------
// The bike is now rented by Daniel for 3 hours.
// A 3 hours bike ride has been started
// ride complete!!
// The bike ran 12 hours.
// [ The bike has been returned ]
// --------------------------------------------------
// The bike is now rented by Bob for 2 hours.
// A 2 hours bike ride has been started
// ride complete!!
// The bike ran 14 hours.
// [ The bike has been returned ]
// ==================================================
// The bike had a total ride of 14 hours
#[cfg(test)]
mod test {
use std::sync::{Arc, Mutex};
use crate::Bike;
#[test]
fn test_lock_unlock() {
let bike = Arc::new(Mutex::new(Bike::new()));
// Lock and mutate
{
let mut guard = bike.lock().unwrap();
guard.ride(5);
assert_eq!(guard.ride_time, 5);
// guard goes out of scope here, lock is released
}
// remember, the first lock is released here as the guard goes out of
// scope, so we can lock it again otherwise it will result in a deadlock
// and the program will hang forever.
// Lock again and mutate
{
let mut guard = bike.lock().unwrap();
guard.ride(3); // total ride time is now 8
assert_eq!(guard.ride_time, 8);
}
}
}