Debian Codegraph @

examples/mutex.rs

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