Skip to content

Commit b134a1f

Browse files
Remove lazily initialized Mutex (#723)
`Mutex::new` is const since 1.63, which is below the 1.82 MSRV, so it should be fine to rely on. Slightly reduces `unsafe` and memory use.
1 parent b65ab93 commit b134a1f

File tree

1 file changed

+5
-14
lines changed

1 file changed

+5
-14
lines changed

src/lib.rs

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -138,17 +138,14 @@ cfg_if::cfg_if! {
138138

139139
#[cfg(feature = "std")]
140140
mod lock {
141-
use std::boxed::Box;
142141
use std::cell::Cell;
143-
use std::ptr;
144-
use std::sync::{Mutex, MutexGuard, Once};
142+
use std::sync::{Mutex, MutexGuard};
145143

146144
/// A "Maybe" LockGuard
147145
pub struct LockGuard(Option<MutexGuard<'static, ()>>);
148146

149-
/// The global lock, lazily allocated on first use
150-
static mut LOCK: *mut Mutex<()> = ptr::null_mut();
151-
static INIT: Once = Once::new();
147+
/// The global lock
148+
static LOCK: Mutex<()> = Mutex::new(());
152149
// Whether this thread is the one that holds the lock
153150
thread_local!(static LOCK_HELD: Cell<bool> = const { Cell::new(false) });
154151

@@ -226,14 +223,8 @@ mod lock {
226223
// Insist that we totally are the thread holding the lock
227224
// (our thread will block until we are)
228225
LOCK_HELD.with(|s| s.set(true));
229-
unsafe {
230-
// lazily allocate the lock if necessary
231-
INIT.call_once(|| {
232-
LOCK = Box::into_raw(Box::new(Mutex::new(())));
233-
});
234-
// ok *actually* try to acquire the lock, blocking as necessary
235-
LockGuard(Some((*LOCK).lock().unwrap()))
236-
}
226+
// ok *actually* try to acquire the lock, blocking as necessary
227+
LockGuard(Some(LOCK.lock().unwrap()))
237228
}
238229
}
239230

0 commit comments

Comments
 (0)