Skip to content

Commit d75cc3b

Browse files
committed
std: use nonpoison::Mutex for all internal mutexes
1 parent 4e0baae commit d75cc3b

File tree

10 files changed

+56
-41
lines changed

10 files changed

+56
-41
lines changed

library/std/src/io/stdio.rs

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,14 @@ use crate::io::{
1212
};
1313
use crate::panic::{RefUnwindSafe, UnwindSafe};
1414
use crate::sync::atomic::{Atomic, AtomicBool, Ordering};
15-
use crate::sync::{Arc, Mutex, MutexGuard, OnceLock, ReentrantLock, ReentrantLockGuard};
15+
use crate::sync::nonpoison::{Mutex, MutexGuard};
16+
use crate::sync::{Arc, OnceLock, ReentrantLock, ReentrantLockGuard, poison};
1617
use crate::sys::stdio;
1718
use crate::thread::AccessError;
1819

19-
type LocalStream = Arc<Mutex<Vec<u8>>>;
20+
// This is explicitly using poisoning, as that affects what gets captured.
21+
// FIXME: maybe change this to a non-poisoning mutex regardless?
22+
type LocalStream = Arc<poison::Mutex<Vec<u8>>>;
2023

2124
thread_local! {
2225
/// Used by the test crate to capture the output of the print macros and panics.
@@ -372,7 +375,7 @@ impl Stdin {
372375
pub fn lock(&self) -> StdinLock<'static> {
373376
// Locks this handle with 'static lifetime. This depends on the
374377
// implementation detail that the underlying `Mutex` is static.
375-
StdinLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
378+
StdinLock { inner: self.inner.lock() }
376379
}
377380

378381
/// Locks this handle and reads a line of input, appending it to the specified buffer.
@@ -434,6 +437,12 @@ impl Stdin {
434437
}
435438
}
436439

440+
#[stable(feature = "catch_unwind", since = "1.9.0")]
441+
impl UnwindSafe for Stdin {}
442+
443+
#[stable(feature = "catch_unwind", since = "1.9.0")]
444+
impl RefUnwindSafe for Stdin {}
445+
437446
#[stable(feature = "std_debug", since = "1.16.0")]
438447
impl fmt::Debug for Stdin {
439448
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
@@ -507,6 +516,12 @@ impl StdinLock<'_> {
507516
}
508517
}
509518

519+
#[stable(feature = "catch_unwind", since = "1.9.0")]
520+
impl UnwindSafe for StdinLock<'_> {}
521+
522+
#[stable(feature = "catch_unwind", since = "1.9.0")]
523+
impl RefUnwindSafe for StdinLock<'_> {}
524+
510525
#[stable(feature = "rust1", since = "1.0.0")]
511526
impl Read for StdinLock<'_> {
512527
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {

library/std/src/io/stdio/tests.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -122,36 +122,36 @@ where
122122
let th1 = {
123123
let (log, tx) = (Arc::clone(&log), tx1);
124124
thread::spawn(move || {
125-
log.lock().unwrap().push(Start1);
125+
log.lock().push(Start1);
126126
let handle = get_handle();
127127
{
128128
let locked = handle.lock();
129-
log.lock().unwrap().push(Acquire1);
129+
log.lock().push(Acquire1);
130130
tx.send(Acquire1).unwrap(); // notify of acquisition
131131
tx.send(Release1).unwrap(); // wait for release command
132-
log.lock().unwrap().push(Release1);
132+
log.lock().push(Release1);
133133
}
134134
tx.send(Acquire1).unwrap(); // wait for th2 acquire
135135
{
136136
let locked = handle.lock();
137-
log.lock().unwrap().push(Acquire1);
137+
log.lock().push(Acquire1);
138138
}
139-
log.lock().unwrap().push(Release1);
139+
log.lock().push(Release1);
140140
})
141141
};
142142
let th2 = {
143143
let (log, tx) = (Arc::clone(&log), tx2);
144144
thread::spawn(move || {
145145
tx.send(Start2).unwrap(); // wait for start command
146146
let locked = get_locked();
147-
log.lock().unwrap().push(Acquire2);
147+
log.lock().push(Acquire2);
148148
tx.send(Acquire2).unwrap(); // notify of acquisition
149149
tx.send(Release2).unwrap(); // wait for release command
150-
log.lock().unwrap().push(Release2);
150+
log.lock().push(Release2);
151151
})
152152
};
153153
assert_eq!(rx1.recv().unwrap(), Acquire1); // wait for th1 acquire
154-
log.lock().unwrap().push(Start2);
154+
log.lock().push(Start2);
155155
assert_eq!(rx2.recv().unwrap(), Start2); // block th2
156156
assert_eq!(rx1.recv().unwrap(), Release1); // release th1
157157
assert_eq!(rx2.recv().unwrap(), Acquire2); // wait for th2 acquire
@@ -160,7 +160,7 @@ where
160160
th2.join().unwrap();
161161
th1.join().unwrap();
162162
assert_eq!(
163-
*log.lock().unwrap(),
163+
*log.lock(),
164164
[Start1, Acquire1, Start2, Release1, Acquire2, Release2, Acquire1, Release1]
165165
);
166166
}

library/std/src/sync/mpmc/waker.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
use super::context::Context;
44
use super::select::{Operation, Selected};
55
use crate::ptr;
6-
use crate::sync::Mutex;
76
use crate::sync::atomic::{Atomic, AtomicBool, Ordering};
7+
use crate::sync::nonpoison::Mutex;
88

99
/// Represents a thread blocked on a specific channel operation.
1010
pub(crate) struct Entry {
@@ -150,7 +150,7 @@ impl SyncWaker {
150150
/// Registers the current thread with an operation.
151151
#[inline]
152152
pub(crate) fn register(&self, oper: Operation, cx: &Context) {
153-
let mut inner = self.inner.lock().unwrap();
153+
let mut inner = self.inner.lock();
154154
inner.register(oper, cx);
155155
self.is_empty
156156
.store(inner.selectors.is_empty() && inner.observers.is_empty(), Ordering::SeqCst);
@@ -159,7 +159,7 @@ impl SyncWaker {
159159
/// Unregisters an operation previously registered by the current thread.
160160
#[inline]
161161
pub(crate) fn unregister(&self, oper: Operation) -> Option<Entry> {
162-
let mut inner = self.inner.lock().unwrap();
162+
let mut inner = self.inner.lock();
163163
let entry = inner.unregister(oper);
164164
self.is_empty
165165
.store(inner.selectors.is_empty() && inner.observers.is_empty(), Ordering::SeqCst);
@@ -170,7 +170,7 @@ impl SyncWaker {
170170
#[inline]
171171
pub(crate) fn notify(&self) {
172172
if !self.is_empty.load(Ordering::SeqCst) {
173-
let mut inner = self.inner.lock().unwrap();
173+
let mut inner = self.inner.lock();
174174
if !self.is_empty.load(Ordering::SeqCst) {
175175
inner.try_select();
176176
inner.notify();
@@ -185,7 +185,7 @@ impl SyncWaker {
185185
/// Notifies all threads that the channel is disconnected.
186186
#[inline]
187187
pub(crate) fn disconnect(&self) {
188-
let mut inner = self.inner.lock().unwrap();
188+
let mut inner = self.inner.lock();
189189
inner.disconnect();
190190
self.is_empty
191191
.store(inner.selectors.is_empty() && inner.observers.is_empty(), Ordering::SeqCst);

library/std/src/sync/mpmc/zero.rs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ use super::utils::Backoff;
99
use super::waker::Waker;
1010
use crate::cell::UnsafeCell;
1111
use crate::marker::PhantomData;
12-
use crate::sync::Mutex;
1312
use crate::sync::atomic::{Atomic, AtomicBool, Ordering};
13+
use crate::sync::nonpoison::Mutex;
1414
use crate::time::Instant;
1515
use crate::{fmt, ptr};
1616

@@ -141,7 +141,7 @@ impl<T> Channel<T> {
141141
/// Attempts to send a message into the channel.
142142
pub(crate) fn try_send(&self, msg: T) -> Result<(), TrySendError<T>> {
143143
let token = &mut Token::default();
144-
let mut inner = self.inner.lock().unwrap();
144+
let mut inner = self.inner.lock();
145145

146146
// If there's a waiting receiver, pair up with it.
147147
if let Some(operation) = inner.receivers.try_select() {
@@ -165,7 +165,7 @@ impl<T> Channel<T> {
165165
deadline: Option<Instant>,
166166
) -> Result<(), SendTimeoutError<T>> {
167167
let token = &mut Token::default();
168-
let mut inner = self.inner.lock().unwrap();
168+
let mut inner = self.inner.lock();
169169

170170
// If there's a waiting receiver, pair up with it.
171171
if let Some(operation) = inner.receivers.try_select() {
@@ -196,12 +196,12 @@ impl<T> Channel<T> {
196196
match sel {
197197
Selected::Waiting => unreachable!(),
198198
Selected::Aborted => {
199-
self.inner.lock().unwrap().senders.unregister(oper).unwrap();
199+
self.inner.lock().senders.unregister(oper).unwrap();
200200
let msg = unsafe { packet.msg.get().replace(None).unwrap() };
201201
Err(SendTimeoutError::Timeout(msg))
202202
}
203203
Selected::Disconnected => {
204-
self.inner.lock().unwrap().senders.unregister(oper).unwrap();
204+
self.inner.lock().senders.unregister(oper).unwrap();
205205
let msg = unsafe { packet.msg.get().replace(None).unwrap() };
206206
Err(SendTimeoutError::Disconnected(msg))
207207
}
@@ -217,7 +217,7 @@ impl<T> Channel<T> {
217217
/// Attempts to receive a message without blocking.
218218
pub(crate) fn try_recv(&self) -> Result<T, TryRecvError> {
219219
let token = &mut Token::default();
220-
let mut inner = self.inner.lock().unwrap();
220+
let mut inner = self.inner.lock();
221221

222222
// If there's a waiting sender, pair up with it.
223223
if let Some(operation) = inner.senders.try_select() {
@@ -234,7 +234,7 @@ impl<T> Channel<T> {
234234
/// Receives a message from the channel.
235235
pub(crate) fn recv(&self, deadline: Option<Instant>) -> Result<T, RecvTimeoutError> {
236236
let token = &mut Token::default();
237-
let mut inner = self.inner.lock().unwrap();
237+
let mut inner = self.inner.lock();
238238

239239
// If there's a waiting sender, pair up with it.
240240
if let Some(operation) = inner.senders.try_select() {
@@ -264,11 +264,11 @@ impl<T> Channel<T> {
264264
match sel {
265265
Selected::Waiting => unreachable!(),
266266
Selected::Aborted => {
267-
self.inner.lock().unwrap().receivers.unregister(oper).unwrap();
267+
self.inner.lock().receivers.unregister(oper).unwrap();
268268
Err(RecvTimeoutError::Timeout)
269269
}
270270
Selected::Disconnected => {
271-
self.inner.lock().unwrap().receivers.unregister(oper).unwrap();
271+
self.inner.lock().receivers.unregister(oper).unwrap();
272272
Err(RecvTimeoutError::Disconnected)
273273
}
274274
Selected::Operation(_) => {
@@ -284,7 +284,7 @@ impl<T> Channel<T> {
284284
///
285285
/// Returns `true` if this call disconnected the channel.
286286
pub(crate) fn disconnect(&self) -> bool {
287-
let mut inner = self.inner.lock().unwrap();
287+
let mut inner = self.inner.lock();
288288

289289
if !inner.is_disconnected {
290290
inner.is_disconnected = true;

library/std/src/sys/backtrace.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use crate::backtrace_rs::{self, BacktraceFmt, BytesOrWideString, PrintFmt};
55
use crate::borrow::Cow;
66
use crate::io::prelude::*;
77
use crate::path::{self, Path, PathBuf};
8-
use crate::sync::{Mutex, MutexGuard, PoisonError};
8+
use crate::sync::nonpoison::{Mutex, MutexGuard};
99
use crate::{env, fmt, io};
1010

1111
/// Max number of frames to print.
@@ -15,7 +15,7 @@ pub(crate) struct BacktraceLock<'a>(#[allow(dead_code)] MutexGuard<'a, ()>);
1515

1616
pub(crate) fn lock<'a>() -> BacktraceLock<'a> {
1717
static LOCK: Mutex<()> = Mutex::new(());
18-
BacktraceLock(LOCK.lock().unwrap_or_else(PoisonError::into_inner))
18+
BacktraceLock(LOCK.lock())
1919
}
2020

2121
impl BacktraceLock<'_> {

library/std/src/sys/env/hermit.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,12 @@ use crate::collections::HashMap;
55
use crate::ffi::{CStr, OsStr, OsString, c_char};
66
use crate::io;
77
use crate::os::hermit::ffi::OsStringExt;
8-
use crate::sync::Mutex;
8+
use crate::sync::nonpoison::Mutex;
99

1010
static ENV: Mutex<Option<HashMap<OsString, OsString>>> = Mutex::new(None);
1111

1212
pub fn init(env: *const *const c_char) {
13-
let mut guard = ENV.lock().unwrap();
13+
let mut guard = ENV.lock();
1414
let map = guard.insert(HashMap::new());
1515

1616
if env.is_null() {
@@ -48,7 +48,7 @@ pub fn init(env: *const *const c_char) {
4848
/// Returns a vector of (variable, value) byte-vector pairs for all the
4949
/// environment variables of the current process.
5050
pub fn env() -> Env {
51-
let guard = ENV.lock().unwrap();
51+
let guard = ENV.lock();
5252
let env = guard.as_ref().unwrap();
5353

5454
let result = env.iter().map(|(key, value)| (key.clone(), value.clone())).collect();
@@ -57,16 +57,16 @@ pub fn env() -> Env {
5757
}
5858

5959
pub fn getenv(k: &OsStr) -> Option<OsString> {
60-
ENV.lock().unwrap().as_ref().unwrap().get(k).cloned()
60+
ENV.lock().as_ref().unwrap().get(k).cloned()
6161
}
6262

6363
pub unsafe fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
6464
let (k, v) = (k.to_owned(), v.to_owned());
65-
ENV.lock().unwrap().as_mut().unwrap().insert(k, v);
65+
ENV.lock().as_mut().unwrap().insert(k, v);
6666
Ok(())
6767
}
6868

6969
pub unsafe fn unsetenv(k: &OsStr) -> io::Result<()> {
70-
ENV.lock().unwrap().as_mut().unwrap().remove(k);
70+
ENV.lock().as_mut().unwrap().remove(k);
7171
Ok(())
7272
}

library/std/src/sys/pal/unix/stack_overflow/thread_info.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@
2727
use crate::collections::BTreeMap;
2828
use crate::hint::spin_loop;
2929
use crate::ops::Range;
30-
use crate::sync::Mutex;
3130
use crate::sync::atomic::{AtomicUsize, Ordering};
31+
use crate::sync::nonpoison::Mutex;
3232
use crate::sys::os::errno_location;
3333

3434
pub struct ThreadInfo {

library/std/src/sys/process/windows.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use crate::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, FromRawHandl
1616
use crate::os::windows::process::ProcThreadAttributeList;
1717
use crate::path::{Path, PathBuf};
1818
use crate::process::StdioPipes;
19-
use crate::sync::Mutex;
19+
use crate::sync::nonpoison::Mutex;
2020
use crate::sys::args::{self, Arg};
2121
use crate::sys::c::{self, EXIT_FAILURE, EXIT_SUCCESS};
2222
use crate::sys::fs::{File, OpenOptions};

library/std/src/sys/thread/sgx.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ pub use self::task_queue::JoinNotifier;
1212

1313
mod task_queue {
1414
use super::wait_notify;
15-
use crate::sync::{Mutex, MutexGuard};
15+
use crate::sync::nonpoison::{Mutex, MutexGuard};
1616

1717
pub type JoinHandle = wait_notify::Waiter;
1818

@@ -48,7 +48,7 @@ mod task_queue {
4848
static TASK_QUEUE: Mutex<Vec<Task>> = Mutex::new(Vec::new());
4949

5050
pub(super) fn lock() -> MutexGuard<'static, Vec<Task>> {
51-
TASK_QUEUE.lock().unwrap()
51+
TASK_QUEUE.lock()
5252
}
5353
}
5454

library/std/src/thread/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1257,11 +1257,11 @@ impl ThreadId {
12571257
}
12581258
}
12591259
_ => {
1260-
use crate::sync::{Mutex, PoisonError};
1260+
use crate::sync::nonpoison::Mutex;
12611261

12621262
static COUNTER: Mutex<u64> = Mutex::new(0);
12631263

1264-
let mut counter = COUNTER.lock().unwrap_or_else(PoisonError::into_inner);
1264+
let mut counter = COUNTER.lock();
12651265
let Some(id) = counter.checked_add(1) else {
12661266
// in case the panic handler ends up calling `ThreadId::new()`,
12671267
// avoid reentrant lock acquire.

0 commit comments

Comments
 (0)