1 | // Copyright 2016 Amanieu d'Antras |
2 | // |
3 | // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or |
4 | // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or |
5 | // http://opensource.org/licenses/MIT>, at your option. This file may not be |
6 | // copied, modified, or distributed except according to those terms. |
7 | |
8 | use crate::raw_mutex::RawMutex; |
9 | use core::num::NonZeroUsize; |
10 | use lock_api::{self, GetThreadId}; |
11 | |
12 | /// Implementation of the `GetThreadId` trait for `lock_api::ReentrantMutex`. |
13 | pub struct RawThreadId; |
14 | |
15 | unsafe impl GetThreadId for RawThreadId { |
16 | const INIT: RawThreadId = RawThreadId; |
17 | |
18 | fn nonzero_thread_id(&self) -> NonZeroUsize { |
19 | // The address of a thread-local variable is guaranteed to be unique to the |
20 | // current thread, and is also guaranteed to be non-zero. The variable has to have a |
21 | // non-zero size to guarantee it has a unique address for each thread. |
22 | thread_local!(static KEY: u8 = 0); |
23 | KEY.with(|x| { |
24 | NonZeroUsize::new(x as *const _ as usize) |
25 | .expect("thread-local variable address is null" ) |
26 | }) |
27 | } |
28 | } |
29 | |
30 | /// A mutex which can be recursively locked by a single thread. |
31 | /// |
32 | /// This type is identical to `Mutex` except for the following points: |
33 | /// |
34 | /// - Locking multiple times from the same thread will work correctly instead of |
35 | /// deadlocking. |
36 | /// - `ReentrantMutexGuard` does not give mutable references to the locked data. |
37 | /// Use a `RefCell` if you need this. |
38 | /// |
39 | /// See [`Mutex`](type.Mutex.html) for more details about the underlying mutex |
40 | /// primitive. |
41 | pub type ReentrantMutex<T> = lock_api::ReentrantMutex<RawMutex, RawThreadId, T>; |
42 | |
43 | /// Creates a new reentrant mutex in an unlocked state ready for use. |
44 | /// |
45 | /// This allows creating a reentrant mutex in a constant context on stable Rust. |
46 | pub const fn const_reentrant_mutex<T>(val: T) -> ReentrantMutex<T> { |
47 | ReentrantMutex::const_new( |
48 | <RawMutex as lock_api::RawMutex>::INIT, |
49 | <RawThreadId as lock_api::GetThreadId>::INIT, |
50 | val, |
51 | ) |
52 | } |
53 | |
54 | /// An RAII implementation of a "scoped lock" of a reentrant mutex. When this structure |
55 | /// is dropped (falls out of scope), the lock will be unlocked. |
56 | /// |
57 | /// The data protected by the mutex can be accessed through this guard via its |
58 | /// `Deref` implementation. |
59 | pub type ReentrantMutexGuard<'a, T> = lock_api::ReentrantMutexGuard<'a, RawMutex, RawThreadId, T>; |
60 | |
61 | /// An RAII mutex guard returned by `ReentrantMutexGuard::map`, which can point to a |
62 | /// subfield of the protected data. |
63 | /// |
64 | /// The main difference between `MappedReentrantMutexGuard` and `ReentrantMutexGuard` is that the |
65 | /// former doesn't support temporarily unlocking and re-locking, since that |
66 | /// could introduce soundness issues if the locked object is modified by another |
67 | /// thread. |
68 | pub type MappedReentrantMutexGuard<'a, T> = |
69 | lock_api::MappedReentrantMutexGuard<'a, RawMutex, RawThreadId, T>; |
70 | |
71 | #[cfg (test)] |
72 | mod tests { |
73 | use crate::ReentrantMutex; |
74 | use std::cell::RefCell; |
75 | use std::sync::Arc; |
76 | use std::thread; |
77 | |
78 | #[cfg (feature = "serde" )] |
79 | use bincode::{deserialize, serialize}; |
80 | |
81 | #[test] |
82 | fn smoke() { |
83 | let m = ReentrantMutex::new(2); |
84 | { |
85 | let a = m.lock(); |
86 | { |
87 | let b = m.lock(); |
88 | { |
89 | let c = m.lock(); |
90 | assert_eq!(*c, 2); |
91 | } |
92 | assert_eq!(*b, 2); |
93 | } |
94 | assert_eq!(*a, 2); |
95 | } |
96 | } |
97 | |
98 | #[test] |
99 | fn is_mutex() { |
100 | let m = Arc::new(ReentrantMutex::new(RefCell::new(0))); |
101 | let m2 = m.clone(); |
102 | let lock = m.lock(); |
103 | let child = thread::spawn(move || { |
104 | let lock = m2.lock(); |
105 | assert_eq!(*lock.borrow(), 4950); |
106 | }); |
107 | for i in 0..100 { |
108 | let lock = m.lock(); |
109 | *lock.borrow_mut() += i; |
110 | } |
111 | drop(lock); |
112 | child.join().unwrap(); |
113 | } |
114 | |
115 | #[test] |
116 | fn trylock_works() { |
117 | let m = Arc::new(ReentrantMutex::new(())); |
118 | let m2 = m.clone(); |
119 | let _lock = m.try_lock(); |
120 | let _lock2 = m.try_lock(); |
121 | thread::spawn(move || { |
122 | let lock = m2.try_lock(); |
123 | assert!(lock.is_none()); |
124 | }) |
125 | .join() |
126 | .unwrap(); |
127 | let _lock3 = m.try_lock(); |
128 | } |
129 | |
130 | #[test] |
131 | fn test_reentrant_mutex_debug() { |
132 | let mutex = ReentrantMutex::new(vec![0u8, 10]); |
133 | |
134 | assert_eq!(format!("{:?}" , mutex), "ReentrantMutex { data: [0, 10] }" ); |
135 | } |
136 | |
137 | #[cfg (feature = "serde" )] |
138 | #[test] |
139 | fn test_serde() { |
140 | let contents: Vec<u8> = vec![0, 1, 2]; |
141 | let mutex = ReentrantMutex::new(contents.clone()); |
142 | |
143 | let serialized = serialize(&mutex).unwrap(); |
144 | let deserialized: ReentrantMutex<Vec<u8>> = deserialize(&serialized).unwrap(); |
145 | |
146 | assert_eq!(*(mutex.lock()), *(deserialized.lock())); |
147 | assert_eq!(contents, *(deserialized.lock())); |
148 | } |
149 | } |
150 | |