forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread_mutex.rs
More file actions
355 lines (332 loc) · 10.6 KB
/
Copy paththread_mutex.rs
File metadata and controls
355 lines (332 loc) · 10.6 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
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
#![allow(clippy::needless_lifetimes)]
use alloc::fmt;
use core::{
cell::UnsafeCell,
marker::PhantomData,
ops::{Deref, DerefMut},
ptr::NonNull,
sync::atomic::{AtomicUsize, Ordering},
};
use lock_api::{GetThreadId, GuardNoSend, RawMutex};
// based off ReentrantMutex from lock_api
/// A mutex type that knows when it would deadlock
pub struct RawThreadMutex<R: RawMutex, G: GetThreadId> {
owner: AtomicUsize,
mutex: R,
get_thread_id: G,
}
impl<R: RawMutex, G: GetThreadId> RawThreadMutex<R, G> {
#[allow(
clippy::declare_interior_mutable_const,
reason = "const initializer for lock primitive contains atomics by design"
)]
pub const INIT: Self = Self {
owner: AtomicUsize::new(0),
mutex: R::INIT,
get_thread_id: G::INIT,
};
#[inline]
fn lock_internal<F: FnOnce() -> bool>(&self, try_lock: F) -> Option<bool> {
let id = self.get_thread_id.nonzero_thread_id().get();
if self.owner.load(Ordering::Relaxed) == id {
return None;
}
if !try_lock() {
return Some(false);
}
self.owner.store(id, Ordering::Relaxed);
Some(true)
}
/// Blocks for the mutex to be available, and returns true if the mutex isn't already
/// locked on the current thread.
pub fn lock(&self) -> bool {
self.lock_internal(|| {
self.mutex.lock();
true
})
.is_some()
}
/// Like `lock()` but wraps the blocking wait in `wrap_fn`.
/// The caller can use this to detach thread state while waiting.
pub fn lock_wrapped<F: FnOnce(&dyn Fn())>(&self, wrap_fn: F) -> bool {
let id = self.get_thread_id.nonzero_thread_id().get();
if self.owner.load(Ordering::Relaxed) == id {
return false;
}
wrap_fn(&|| self.mutex.lock());
self.owner.store(id, Ordering::Relaxed);
true
}
/// Returns `Some(true)` if able to successfully lock without blocking, `Some(false)`
/// otherwise, and `None` when the mutex is already locked on the current thread.
pub fn try_lock(&self) -> Option<bool> {
self.lock_internal(|| self.mutex.try_lock())
}
/// Unlocks this mutex. The inner mutex may not be unlocked if
/// this mutex was acquired previously in the current thread.
///
/// # Safety
///
/// This method may only be called if the mutex is held by the current thread.
pub unsafe fn unlock(&self) {
self.owner.store(0, Ordering::Relaxed);
unsafe { self.mutex.unlock() };
}
}
impl<R: RawMutex, G: GetThreadId> RawThreadMutex<R, G> {
/// Reset this mutex to its initial (unlocked, unowned) state after `fork()`.
///
/// # Safety
///
/// Must only be called from the single-threaded child process immediately
/// after `fork()`, before any other thread is created.
#[cfg(unix)]
pub unsafe fn reinit_after_fork(&self) {
self.owner.store(0, Ordering::Relaxed);
unsafe {
let mutex_ptr = &self.mutex as *const R as *mut u8;
core::ptr::write_bytes(mutex_ptr, 0, core::mem::size_of::<R>());
}
}
}
unsafe impl<R: RawMutex + Send, G: GetThreadId + Send> Send for RawThreadMutex<R, G> {}
unsafe impl<R: RawMutex + Sync, G: GetThreadId + Sync> Sync for RawThreadMutex<R, G> {}
pub struct ThreadMutex<R: RawMutex, G: GetThreadId, T: ?Sized> {
raw: RawThreadMutex<R, G>,
data: UnsafeCell<T>,
}
impl<R: RawMutex, G: GetThreadId, T> ThreadMutex<R, G, T> {
pub const fn new(val: T) -> Self {
Self {
raw: RawThreadMutex::INIT,
data: UnsafeCell::new(val),
}
}
pub fn into_inner(self) -> T {
self.data.into_inner()
}
}
impl<R: RawMutex, G: GetThreadId, T: Default> Default for ThreadMutex<R, G, T> {
fn default() -> Self {
Self::new(T::default())
}
}
impl<R: RawMutex, G: GetThreadId, T> From<T> for ThreadMutex<R, G, T> {
fn from(val: T) -> Self {
Self::new(val)
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized> ThreadMutex<R, G, T> {
/// Access the underlying raw thread mutex.
pub fn raw(&self) -> &RawThreadMutex<R, G> {
&self.raw
}
pub fn lock(&self) -> Option<ThreadMutexGuard<'_, R, G, T>> {
if self.raw.lock() {
Some(ThreadMutexGuard {
mu: self,
marker: PhantomData,
})
} else {
None
}
}
/// Like `lock()` but wraps the blocking wait in `wrap_fn`.
/// The caller can use this to detach thread state while waiting.
pub fn lock_wrapped<F: FnOnce(&dyn Fn())>(
&self,
wrap_fn: F,
) -> Option<ThreadMutexGuard<'_, R, G, T>> {
if self.raw.lock_wrapped(wrap_fn) {
Some(ThreadMutexGuard {
mu: self,
marker: PhantomData,
})
} else {
None
}
}
pub fn try_lock(&self) -> Result<ThreadMutexGuard<'_, R, G, T>, TryLockThreadError> {
match self.raw.try_lock() {
Some(true) => Ok(ThreadMutexGuard {
mu: self,
marker: PhantomData,
}),
Some(false) => Err(TryLockThreadError::Other),
None => Err(TryLockThreadError::Current),
}
}
}
#[derive(Clone, Copy)]
pub enum TryLockThreadError {
/// Failed to lock because mutex was already locked on another thread.
Other,
/// Failed to lock because mutex was already locked on current thread.
Current,
}
struct LockedPlaceholder(&'static str);
impl fmt::Debug for LockedPlaceholder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.0)
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized + fmt::Debug> fmt::Debug for ThreadMutex<R, G, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.try_lock() {
Ok(guard) => f
.debug_struct("ThreadMutex")
.field("data", &&*guard)
.finish(),
Err(e) => {
let msg = match e {
TryLockThreadError::Other => "<locked on other thread>",
TryLockThreadError::Current => "<locked on current thread>",
};
f.debug_struct("ThreadMutex")
.field("data", &LockedPlaceholder(msg))
.finish()
}
}
}
}
unsafe impl<R: RawMutex + Send, G: GetThreadId + Send, T: ?Sized + Send> Send
for ThreadMutex<R, G, T>
{
}
unsafe impl<R: RawMutex + Sync, G: GetThreadId + Sync, T: ?Sized + Send> Sync
for ThreadMutex<R, G, T>
{
}
pub struct ThreadMutexGuard<'a, R: RawMutex, G: GetThreadId, T: ?Sized> {
mu: &'a ThreadMutex<R, G, T>,
marker: PhantomData<(&'a mut T, GuardNoSend)>,
}
impl<'a, R: RawMutex, G: GetThreadId, T: ?Sized> ThreadMutexGuard<'a, R, G, T> {
pub fn map<U, F: FnOnce(&mut T) -> &mut U>(
mut s: Self,
f: F,
) -> MappedThreadMutexGuard<'a, R, G, U> {
let data = f(&mut s).into();
let mu = &s.mu.raw;
core::mem::forget(s);
MappedThreadMutexGuard {
mu,
data,
marker: PhantomData,
}
}
pub fn try_map<U, F: FnOnce(&mut T) -> Option<&mut U>>(
mut s: Self,
f: F,
) -> Result<MappedThreadMutexGuard<'a, R, G, U>, Self> {
if let Some(data) = f(&mut s) {
let data = data.into();
let mu = &s.mu.raw;
core::mem::forget(s);
Ok(MappedThreadMutexGuard {
mu,
data,
marker: PhantomData,
})
} else {
Err(s)
}
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized> Deref for ThreadMutexGuard<'_, R, G, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.mu.data.get() }
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized> DerefMut for ThreadMutexGuard<'_, R, G, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.mu.data.get() }
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized> Drop for ThreadMutexGuard<'_, R, G, T> {
fn drop(&mut self) {
unsafe { self.mu.raw.unlock() }
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized + fmt::Display> fmt::Display
for ThreadMutexGuard<'_, R, G, T>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized + fmt::Debug> fmt::Debug
for ThreadMutexGuard<'_, R, G, T>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
pub struct MappedThreadMutexGuard<'a, R: RawMutex, G: GetThreadId, T: ?Sized> {
mu: &'a RawThreadMutex<R, G>,
data: NonNull<T>,
marker: PhantomData<(&'a mut T, GuardNoSend)>,
}
impl<'a, R: RawMutex, G: GetThreadId, T: ?Sized> MappedThreadMutexGuard<'a, R, G, T> {
pub fn map<U, F: FnOnce(&mut T) -> &mut U>(
mut s: Self,
f: F,
) -> MappedThreadMutexGuard<'a, R, G, U> {
let data = f(&mut s).into();
let mu = s.mu;
core::mem::forget(s);
MappedThreadMutexGuard {
mu,
data,
marker: PhantomData,
}
}
pub fn try_map<U, F: FnOnce(&mut T) -> Option<&mut U>>(
mut s: Self,
f: F,
) -> Result<MappedThreadMutexGuard<'a, R, G, U>, Self> {
if let Some(data) = f(&mut s) {
let data = data.into();
let mu = s.mu;
core::mem::forget(s);
Ok(MappedThreadMutexGuard {
mu,
data,
marker: PhantomData,
})
} else {
Err(s)
}
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized> Deref for MappedThreadMutexGuard<'_, R, G, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { self.data.as_ref() }
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized> DerefMut for MappedThreadMutexGuard<'_, R, G, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { self.data.as_mut() }
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized> Drop for MappedThreadMutexGuard<'_, R, G, T> {
fn drop(&mut self) {
unsafe { self.mu.unlock() }
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized + fmt::Display> fmt::Display
for MappedThreadMutexGuard<'_, R, G, T>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized + fmt::Debug> fmt::Debug
for MappedThreadMutexGuard<'_, R, G, T>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}