forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

sync.rs178 lines, 4.2 KiBHistoryRawDownload
1#[cfg(loom)]
2pub use loom::thread;
3#[cfg(not(loom))]
4pub use std::thread;
5
6#[cfg(loom)]
7mod raw {
8 pub use loom::sync::{
9 LockResult, Mutex as RawMutex, MutexGuard, RwLock as RawRwLock, RwLockReadGuard,
10 RwLockWriteGuard,
11 };
12}
13#[cfg(not(loom))]
14mod raw {
15 pub use std::sync::{
16 LockResult, Mutex as RawMutex, MutexGuard, RwLock as RawRwLock, RwLockReadGuard,
17 RwLockWriteGuard,
18 };
19}
20
21pub use raw::{MutexGuard, RwLockReadGuard, RwLockWriteGuard};
22
23#[cfg(loom)]
24pub use loom::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicU8, AtomicUsize};
25#[cfg(not(loom))]
26pub use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicU8, AtomicUsize};
27
28#[cfg(loom)]
29pub(crate) use my_thread_local::ThreadLocal;
30#[cfg(not(loom))]
31pub(crate) use thread_local::ThreadLocal;
32
33fn expect_not_poisoned<T>(result: raw::LockResult<T>, lock_kind: &str) -> T {
34 result.unwrap_or_else(|_| panic!("poisoned {lock_kind}"))
35}
36
37#[derive(Debug)]
38pub struct Mutex<T: ?Sized> {
39 inner: raw::RawMutex<T>,
40}
41
42impl<T> Mutex<T> {
43 pub fn new(value: T) -> Self {
44 Self {
45 inner: raw::RawMutex::new(value),
46 }
47 }
48}
49
50impl<T: ?Sized> Mutex<T> {
51 pub fn lock(&self) -> MutexGuard<'_, T> {
52 self.lock_with_kind("mutex")
53 }
54
55 pub(crate) fn lock_with_kind(&self, lock_kind: &str) -> MutexGuard<'_, T> {
56 expect_not_poisoned(self.inner.lock(), lock_kind)
57 }
58
59 /// For locks whose protected state stays valid across a panic (it is
60 /// restored by RAII during unwinding), so one panic does not block every
61 /// later caller.
62 pub(crate) fn lock_ignoring_poison(&self) -> MutexGuard<'_, T> {
63 self.inner
64 .lock()
65 .unwrap_or_else(|poisoned| poisoned.into_inner())
66 }
67
68 pub(crate) fn is_locked(&self) -> bool {
69 self.inner.try_lock().is_err()
70 }
71}
72
73impl<T: Default> Default for Mutex<T> {
74 fn default() -> Self {
75 Self::new(T::default())
76 }
77}
78
79#[derive(Debug)]
80pub struct RwLock<T> {
81 inner: raw::RawRwLock<T>,
82}
83
84impl<T> RwLock<T> {
85 pub fn new(value: T) -> Self {
86 Self {
87 inner: raw::RawRwLock::new(value),
88 }
89 }
90
91 pub fn into_inner(self) -> T {
92 expect_not_poisoned(self.inner.into_inner(), "rwlock")
93 }
94}
95
96impl<T> RwLock<T> {
97 pub fn read(&self) -> RwLockReadGuard<'_, T> {
98 expect_not_poisoned(self.inner.read(), "rwlock")
99 }
100
101 pub fn write(&self) -> RwLockWriteGuard<'_, T> {
102 expect_not_poisoned(self.inner.write(), "rwlock")
103 }
104}
105
106impl<T: Default> Default for RwLock<T> {
107 fn default() -> Self {
108 Self::new(T::default())
109 }
110}
111
112#[cfg(loom)]
113mod my_thread_local {
114 use std::sync::Arc;
115
116 use super::thread;
117 use super::Mutex;
118 use rustc_hash::FxHashMap;
119
120 #[derive(Debug)]
121 pub(crate) struct ThreadLocal<T> {
122 content: Arc<Mutex<FxHashMap<thread::ThreadId, Arc<T>>>>,
123 }
124
125 impl<T: Default> ThreadLocal<T> {
126 pub fn new() -> Self {
127 Self {
128 content: Arc::new(Mutex::new(FxHashMap::default())),
129 }
130 }
131
132 pub fn get_or_default(&self) -> Arc<T> {
133 let mut content = self.content.lock();
134 let v = content
135 .entry(thread::current().id())
136 .or_insert_with(|| Arc::new(T::default()));
137 v.clone()
138 }
139 }
140
141 impl<T> Clone for ThreadLocal<T> {
142 fn clone(&self) -> Self {
143 Self {
144 content: self.content.clone(),
145 }
146 }
147 }
148}
149
150#[cfg(test)]
151mod tests {
152 use super::*;
153
154 #[test]
155 #[should_panic(expected = "poisoned mutex")]
156 fn mutex_lock_panics_after_poison() {
157 let lock = Mutex::new(7);
158 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
159 let _guard = lock.lock();
160 panic!("poison mutex");
161 }));
162
163 drop(lock.lock());
164 }
165
166 #[test]
167 #[should_panic(expected = "poisoned rwlock")]
168 fn rwlock_read_panics_after_poison() {
169 let lock = RwLock::new(7);
170 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
171 let mut guard = lock.write();
172 *guard = 9;
173 panic!("poison rwlock");
174 }));
175
176 drop(lock.read());
177 }
178}