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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
use UnsafeCell;
use PhantomData;
use RawMutex;
use cratePoisonFlag;
use crateThreadKey;
/// A spinning mutex
pub type SpinLock<T> = ;
/// A parking lot mutex
pub type ParkingMutex<T> = ;
/// A mutual exclusion primitive useful for protecting shared data, which
/// cannot deadlock.
///
/// This mutex will block threads waiting for the lock to become available. The
/// mutex can be created via a `new` constructor. Each mutex has a type
/// parameter which represents the data that it is protecting. The data can
/// only be accessed through the [`MutexGuard`]s returned from [`lock`] and
/// [`try_lock`], which guarantees that the data is only ever accessed when
/// the mutex is locked.
///
/// Locking the mutex on a thread that already locked it is impossible, due to
/// the requirement of the [`ThreadKey`]. Therefore, this will never deadlock.
///
/// # Examples
///
/// ```
/// use std::sync::Arc;
/// use std::thread;
/// use std::sync::mpsc;
///
/// use happylock::{Mutex, ThreadKey};
///
/// // Spawn a few threads to increment a shared variable (non-atomically),
/// // and let the main thread know once all increments are done.
/// //
/// // Here we're using an Arc to share memory among threads, and the data
/// // inside the Arc is protected with a mutex.
/// const N: usize = 10;
///
/// let data = Arc::new(Mutex::new(0));
///
/// let (tx, rx) = mpsc::channel();
/// for _ in 0..N {
/// let (data, tx) = (Arc::clone(&data), tx.clone());
/// thread::spawn(move || {
/// let key = ThreadKey::get().unwrap();
/// let mut data = data.lock(key);
/// *data += 1;
/// if *data == N {
/// tx.send(()).unwrap();
/// }
/// // the lock is unlocked
/// });
/// }
///
/// rx.recv().unwrap();
/// ```
///
/// To unlock a mutex guard sooner than the end of the enclosing scope, either
/// create an inner scope, drop the guard manually, or call [`Mutex::unlock`].
///
/// ```
/// use std::sync::Arc;
/// use std::thread;
///
/// use happylock::{Mutex, ThreadKey};
///
/// const N: usize = 3;
///
/// let data_mutex = Arc::new(Mutex::new(vec![1, 2, 3, 4]));
/// let res_mutex = Arc::new(Mutex::new(0));
///
/// let mut threads = Vec::with_capacity(N);
/// (0..N).for_each(|_| {
/// let data_mutex_clone = Arc::clone(&data_mutex);
/// let res_mutex_clone = Arc::clone(&res_mutex);
///
/// threads.push(thread::spawn(move || {
/// let mut key = ThreadKey::get().unwrap();
///
/// // Here we use a block to limit the lifetime of the lock guard.
/// let result = data_mutex_clone.scoped_lock(&mut key, |data| {
/// let result = data.iter().fold(0, |acc, x| acc + x * 2);
/// data.push(result);
/// result
/// // The mutex guard gets dropped here, so the lock is released
/// });
/// // The thread key is available again
/// *res_mutex_clone.lock(key) += result;
/// }));
/// });
///
/// let key = ThreadKey::get().unwrap();
/// let mut data = data_mutex.lock(key);
/// let result = data.iter().fold(0, |acc, x| acc + x * 2);
/// data.push(result);
///
/// // We drop the `data` explicitly because it's not necessary anymore. This
/// // allows other threads to start working on the data immediately. Dropping
/// // the data also gives us access to the thread key, so we can lock
/// // another mutex.
/// let key = Mutex::unlock(data);
///
/// // Here the mutex guard is not assigned to a variable and so, even if the
/// // scope does not end after this line, the mutex is still released: there is
/// // no deadlock.
/// *res_mutex.lock(key) += result;
///
/// threads.into_iter().for_each(|thread| {
/// thread
/// .join()
/// .expect("The thread creating or execution failed !")
/// });
///
/// let key = ThreadKey::get().unwrap();
/// assert_eq!(*res_mutex.lock(key), 800);
/// ```
///
/// [`lock`]: `Mutex::lock`
/// [`try_lock`]: `Mutex::try_lock`
/// [`ThreadKey`]: `crate::ThreadKey`
/// An RAII implementation of a “scoped lock” of a mutex. When this structure
/// is dropped (falls out of scope), the lock will be unlocked.
///
/// The data protected by the mutex can be accessed through this guard via its
/// [`Deref`] and [`DerefMut`] implementations.
///
/// This is created by calling the [`lock`] and [`try_lock`] methods on [`Mutex`]
///
/// This is similar to the [`MutexGuard`] type, except it does not hold a
/// [`ThreadKey`].
///
/// [`lock`]: `Mutex::lock`
/// [`try_lock`]: `Mutex::try_lock`
/// [`Deref`]: `std::ops::Deref`
/// [`DerefMut`]: `std::ops::DerefMut`
;
/// An RAII implementation of a “scoped lock” of a mutex. When this structure
/// is dropped (falls out of scope), the lock will be unlocked.
///
/// The data protected by the mutex can be accessed through this guard via its
/// [`Deref`] and [`DerefMut`] implementations.
///
/// This is created by calling the [`lock`] and [`try_lock`] methods on [`Mutex`]
///
/// This guard holds on to a [`ThreadKey`], which ensures that nothing else is
/// locked until this guard is dropped. The [`ThreadKey`] can be reacquired
/// using [`Mutex::unlock`].
///
/// [`Deref`]: `std::ops::Deref`
/// [`DerefMut`]: `std::ops::DerefMut`
/// [`lock`]: `Mutex::lock`
/// [`try_lock`]: `Mutex::try_lock`
//
// This is the most lifetime-intensive thing I've ever written. Can I graduate
// from borrow checker university now?