|
4 | 4 |
|
5 | 5 | #![allow(dead_code)]
|
6 | 6 |
|
7 |
| -use std::cell::UnsafeCell; |
8 |
| -use std::ops::{Deref, DerefMut}; |
9 |
| -use std::sync::atomic::{AtomicBool, Ordering}; |
10 |
| -use std::sync::{mpsc, Arc}; |
11 |
| -use std::thread; |
12 |
| -use std::time::{Duration, Instant}; |
13 |
| - |
14 |
| -use event_listener::{Event, Listener}; |
15 |
| - |
16 |
| -/// A simple mutex. |
17 |
| -struct Mutex<T> { |
18 |
| - /// Set to `true` when the mutex is locked. |
19 |
| - locked: AtomicBool, |
20 |
| - |
21 |
| - /// Blocked lock operations. |
22 |
| - lock_ops: Event, |
23 |
| - |
24 |
| - /// The inner protected data. |
25 |
| - data: UnsafeCell<T>, |
26 |
| -} |
| 7 | +#[cfg(feature = "std")] |
| 8 | +mod ex { |
| 9 | + use std::cell::UnsafeCell; |
| 10 | + use std::ops::{Deref, DerefMut}; |
| 11 | + use std::sync::atomic::{AtomicBool, Ordering}; |
| 12 | + use std::sync::{mpsc, Arc}; |
| 13 | + use std::thread; |
| 14 | + use std::time::{Duration, Instant}; |
| 15 | + |
| 16 | + use event_listener::{Event, Listener}; |
| 17 | + |
| 18 | + /// A simple mutex. |
| 19 | + struct Mutex<T> { |
| 20 | + /// Set to `true` when the mutex is locked. |
| 21 | + locked: AtomicBool, |
| 22 | + |
| 23 | + /// Blocked lock operations. |
| 24 | + lock_ops: Event, |
| 25 | + |
| 26 | + /// The inner protected data. |
| 27 | + data: UnsafeCell<T>, |
| 28 | + } |
27 | 29 |
|
28 |
| -unsafe impl<T: Send> Send for Mutex<T> {} |
29 |
| -unsafe impl<T: Send> Sync for Mutex<T> {} |
| 30 | + unsafe impl<T: Send> Send for Mutex<T> {} |
| 31 | + unsafe impl<T: Send> Sync for Mutex<T> {} |
30 | 32 |
|
31 |
| -impl<T> Mutex<T> { |
32 |
| - /// Creates a mutex. |
33 |
| - fn new(t: T) -> Mutex<T> { |
34 |
| - Mutex { |
35 |
| - locked: AtomicBool::new(false), |
36 |
| - lock_ops: Event::new(), |
37 |
| - data: UnsafeCell::new(t), |
| 33 | + impl<T> Mutex<T> { |
| 34 | + /// Creates a mutex. |
| 35 | + fn new(t: T) -> Mutex<T> { |
| 36 | + Mutex { |
| 37 | + locked: AtomicBool::new(false), |
| 38 | + lock_ops: Event::new(), |
| 39 | + data: UnsafeCell::new(t), |
| 40 | + } |
38 | 41 | }
|
39 |
| - } |
40 | 42 |
|
41 |
| - /// Attempts to acquire a lock. |
42 |
| - fn try_lock(&self) -> Option<MutexGuard<'_, T>> { |
43 |
| - if !self.locked.swap(true, Ordering::Acquire) { |
44 |
| - Some(MutexGuard(self)) |
45 |
| - } else { |
46 |
| - None |
| 43 | + /// Attempts to acquire a lock. |
| 44 | + fn try_lock(&self) -> Option<MutexGuard<'_, T>> { |
| 45 | + if !self.locked.swap(true, Ordering::Acquire) { |
| 46 | + Some(MutexGuard(self)) |
| 47 | + } else { |
| 48 | + None |
| 49 | + } |
47 | 50 | }
|
48 |
| - } |
49 |
| - |
50 |
| - /// Blocks until a lock is acquired. |
51 |
| - fn lock(&self) -> MutexGuard<'_, T> { |
52 |
| - let mut listener = None; |
53 | 51 |
|
54 |
| - loop { |
55 |
| - // Attempt grabbing a lock. |
56 |
| - if let Some(guard) = self.try_lock() { |
57 |
| - return guard; |
58 |
| - } |
| 52 | + /// Blocks until a lock is acquired. |
| 53 | + fn lock(&self) -> MutexGuard<'_, T> { |
| 54 | + let mut listener = None; |
59 | 55 |
|
60 |
| - // Set up an event listener or wait for a notification. |
61 |
| - match listener.take() { |
62 |
| - None => { |
63 |
| - // Start listening and then try locking again. |
64 |
| - listener = Some(self.lock_ops.listen()); |
| 56 | + loop { |
| 57 | + // Attempt grabbing a lock. |
| 58 | + if let Some(guard) = self.try_lock() { |
| 59 | + return guard; |
65 | 60 | }
|
66 |
| - Some(l) => { |
67 |
| - // Wait until a notification is received. |
68 |
| - l.wait(); |
| 61 | + |
| 62 | + // Set up an event listener or wait for a notification. |
| 63 | + match listener.take() { |
| 64 | + None => { |
| 65 | + // Start listening and then try locking again. |
| 66 | + listener = Some(self.lock_ops.listen()); |
| 67 | + } |
| 68 | + Some(l) => { |
| 69 | + // Wait until a notification is received. |
| 70 | + l.wait(); |
| 71 | + } |
69 | 72 | }
|
70 | 73 | }
|
71 | 74 | }
|
72 |
| - } |
73 |
| - |
74 |
| - /// Blocks until a lock is acquired or the timeout is reached. |
75 |
| - fn lock_timeout(&self, timeout: Duration) -> Option<MutexGuard<'_, T>> { |
76 |
| - let deadline = Instant::now() + timeout; |
77 |
| - let mut listener = None; |
78 | 75 |
|
79 |
| - loop { |
80 |
| - // Attempt grabbing a lock. |
81 |
| - if let Some(guard) = self.try_lock() { |
82 |
| - return Some(guard); |
83 |
| - } |
| 76 | + /// Blocks until a lock is acquired or the timeout is reached. |
| 77 | + fn lock_timeout(&self, timeout: Duration) -> Option<MutexGuard<'_, T>> { |
| 78 | + let deadline = Instant::now() + timeout; |
| 79 | + let mut listener = None; |
84 | 80 |
|
85 |
| - // Set up an event listener or wait for an event. |
86 |
| - match listener.take() { |
87 |
| - None => { |
88 |
| - // Start listening and then try locking again. |
89 |
| - listener = Some(self.lock_ops.listen()); |
| 81 | + loop { |
| 82 | + // Attempt grabbing a lock. |
| 83 | + if let Some(guard) = self.try_lock() { |
| 84 | + return Some(guard); |
90 | 85 | }
|
91 |
| - Some(l) => { |
92 |
| - // Wait until a notification is received. |
93 |
| - if l.wait_deadline(deadline).is_none() { |
94 |
| - return None; |
| 86 | + |
| 87 | + // Set up an event listener or wait for an event. |
| 88 | + match listener.take() { |
| 89 | + None => { |
| 90 | + // Start listening and then try locking again. |
| 91 | + listener = Some(self.lock_ops.listen()); |
| 92 | + } |
| 93 | + Some(l) => { |
| 94 | + // Wait until a notification is received. |
| 95 | + l.wait_deadline(deadline)?; |
95 | 96 | }
|
96 | 97 | }
|
97 | 98 | }
|
98 | 99 | }
|
99 |
| - } |
100 | 100 |
|
101 |
| - /// Acquires a lock asynchronously. |
102 |
| - async fn lock_async(&self) -> MutexGuard<'_, T> { |
103 |
| - let mut listener = None; |
104 |
| - |
105 |
| - loop { |
106 |
| - // Attempt grabbing a lock. |
107 |
| - if let Some(guard) = self.try_lock() { |
108 |
| - return guard; |
109 |
| - } |
| 101 | + /// Acquires a lock asynchronously. |
| 102 | + async fn lock_async(&self) -> MutexGuard<'_, T> { |
| 103 | + let mut listener = None; |
110 | 104 |
|
111 |
| - // Set up an event listener or wait for an event. |
112 |
| - match listener.take() { |
113 |
| - None => { |
114 |
| - // Start listening and then try locking again. |
115 |
| - listener = Some(self.lock_ops.listen()); |
| 105 | + loop { |
| 106 | + // Attempt grabbing a lock. |
| 107 | + if let Some(guard) = self.try_lock() { |
| 108 | + return guard; |
116 | 109 | }
|
117 |
| - Some(l) => { |
118 |
| - // Wait until a notification is received. |
119 |
| - l.await; |
| 110 | + |
| 111 | + // Set up an event listener or wait for an event. |
| 112 | + match listener.take() { |
| 113 | + None => { |
| 114 | + // Start listening and then try locking again. |
| 115 | + listener = Some(self.lock_ops.listen()); |
| 116 | + } |
| 117 | + Some(l) => { |
| 118 | + // Wait until a notification is received. |
| 119 | + l.await; |
| 120 | + } |
120 | 121 | }
|
121 | 122 | }
|
122 | 123 | }
|
123 | 124 | }
|
124 |
| -} |
125 | 125 |
|
126 |
| -/// A guard holding a lock. |
127 |
| -struct MutexGuard<'a, T>(&'a Mutex<T>); |
| 126 | + /// A guard holding a lock. |
| 127 | + struct MutexGuard<'a, T>(&'a Mutex<T>); |
128 | 128 |
|
129 |
| -unsafe impl<T: Send> Send for MutexGuard<'_, T> {} |
130 |
| -unsafe impl<T: Sync> Sync for MutexGuard<'_, T> {} |
| 129 | + unsafe impl<T: Send> Send for MutexGuard<'_, T> {} |
| 130 | + unsafe impl<T: Sync> Sync for MutexGuard<'_, T> {} |
131 | 131 |
|
132 |
| -impl<T> Drop for MutexGuard<'_, T> { |
133 |
| - fn drop(&mut self) { |
134 |
| - self.0.locked.store(false, Ordering::Release); |
135 |
| - self.0.lock_ops.notify(1); |
| 132 | + impl<T> Drop for MutexGuard<'_, T> { |
| 133 | + fn drop(&mut self) { |
| 134 | + self.0.locked.store(false, Ordering::Release); |
| 135 | + self.0.lock_ops.notify(1); |
| 136 | + } |
136 | 137 | }
|
137 |
| -} |
138 | 138 |
|
139 |
| -impl<T> Deref for MutexGuard<'_, T> { |
140 |
| - type Target = T; |
| 139 | + impl<T> Deref for MutexGuard<'_, T> { |
| 140 | + type Target = T; |
141 | 141 |
|
142 |
| - fn deref(&self) -> &T { |
143 |
| - unsafe { &*self.0.data.get() } |
| 142 | + fn deref(&self) -> &T { |
| 143 | + unsafe { &*self.0.data.get() } |
| 144 | + } |
144 | 145 | }
|
145 |
| -} |
146 | 146 |
|
147 |
| -impl<T> DerefMut for MutexGuard<'_, T> { |
148 |
| - fn deref_mut(&mut self) -> &mut T { |
149 |
| - unsafe { &mut *self.0.data.get() } |
| 147 | + impl<T> DerefMut for MutexGuard<'_, T> { |
| 148 | + fn deref_mut(&mut self) -> &mut T { |
| 149 | + unsafe { &mut *self.0.data.get() } |
| 150 | + } |
150 | 151 | }
|
151 |
| -} |
152 | 152 |
|
153 |
| -fn main() { |
154 |
| - const N: usize = 10; |
| 153 | + pub(crate) fn entry() { |
| 154 | + const N: usize = 10; |
155 | 155 |
|
156 |
| - // A shared counter. |
157 |
| - let counter = Arc::new(Mutex::new(0)); |
| 156 | + // A shared counter. |
| 157 | + let counter = Arc::new(Mutex::new(0)); |
158 | 158 |
|
159 |
| - // A channel that signals when all threads are done. |
160 |
| - let (tx, rx) = mpsc::channel(); |
| 159 | + // A channel that signals when all threads are done. |
| 160 | + let (tx, rx) = mpsc::channel(); |
161 | 161 |
|
162 |
| - // Spawn a bunch of threads incrementing the counter. |
163 |
| - for _ in 0..N { |
164 |
| - let counter = counter.clone(); |
165 |
| - let tx = tx.clone(); |
| 162 | + // Spawn a bunch of threads incrementing the counter. |
| 163 | + for _ in 0..N { |
| 164 | + let counter = counter.clone(); |
| 165 | + let tx = tx.clone(); |
166 | 166 |
|
167 |
| - thread::spawn(move || { |
168 |
| - let mut counter = counter.lock(); |
169 |
| - *counter += 1; |
| 167 | + thread::spawn(move || { |
| 168 | + let mut counter = counter.lock(); |
| 169 | + *counter += 1; |
170 | 170 |
|
171 |
| - // If this is the last increment, signal that we're done. |
172 |
| - if *counter == N { |
173 |
| - tx.send(()).unwrap(); |
174 |
| - } |
175 |
| - }); |
176 |
| - } |
| 171 | + // If this is the last increment, signal that we're done. |
| 172 | + if *counter == N { |
| 173 | + tx.send(()).unwrap(); |
| 174 | + } |
| 175 | + }); |
| 176 | + } |
177 | 177 |
|
178 |
| - // Wait until the last thread increments the counter. |
179 |
| - rx.recv().unwrap(); |
| 178 | + // Wait until the last thread increments the counter. |
| 179 | + rx.recv().unwrap(); |
180 | 180 |
|
181 |
| - // The counter must equal the number of threads. |
182 |
| - assert_eq!(*counter.lock(), N); |
| 181 | + // The counter must equal the number of threads. |
| 182 | + assert_eq!(*counter.lock(), N); |
183 | 183 |
|
184 |
| - println!("Done!"); |
| 184 | + println!("Done!"); |
| 185 | + } |
| 186 | +} |
| 187 | + |
| 188 | +#[cfg(not(feature = "std"))] |
| 189 | +mod ex { |
| 190 | + pub(crate) fn entry() { |
| 191 | + eprintln!("this example requires the 'std' feature") |
| 192 | + } |
| 193 | +} |
| 194 | + |
| 195 | +fn main() { |
| 196 | + ex::entry(); |
185 | 197 | }
|
0 commit comments