Skip to content

Commit d9e06c4

Browse files
committed
std: refactor pthread-based synchronization
The non-trivial code for `pthread_condvar` is duplicated across the thread parking and the `Mutex`/`Condvar` implementations. This PR moves that code into `sys::pal`, which now exposes an `unsafe` wrapper type for `pthread_mutex_t` and `pthread_condvar_t`. Additionally, this PR replaces `LazyBox` with `OnceBox`, thus simplifying the allocation logic.
1 parent 1ddedba commit d9e06c4

File tree

13 files changed

+536
-542
lines changed

13 files changed

+536
-542
lines changed

Diff for: library/std/src/sys/pal/unix/mod.rs

+10
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,16 @@ pub mod process;
3131
pub mod rand;
3232
pub mod stack_overflow;
3333
pub mod stdio;
34+
#[cfg(not(any(
35+
target_os = "linux",
36+
target_os = "android",
37+
all(target_os = "emscripten", target_feature = "atomics"),
38+
target_os = "freebsd",
39+
target_os = "openbsd",
40+
target_os = "dragonfly",
41+
target_os = "fuchsia",
42+
)))]
43+
pub mod sync;
3444
pub mod thread;
3545
pub mod thread_parking;
3646
pub mod time;

Diff for: library/std/src/sys/pal/unix/sync/condvar.rs

+170
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
use super::Mutex;
2+
use crate::cell::UnsafeCell;
3+
use crate::pin::Pin;
4+
use crate::sys::pal::time::Timespec;
5+
#[cfg(not(target_os = "nto"))]
6+
use crate::sys::pal::time::TIMESPEC_MAX;
7+
#[cfg(target_os = "nto")]
8+
use crate::sys::pal::time::TIMESPEC_MAX_CAPPED;
9+
use crate::time::Duration;
10+
11+
pub struct Condvar {
12+
inner: UnsafeCell<libc::pthread_cond_t>,
13+
}
14+
15+
impl Condvar {
16+
pub fn new() -> Condvar {
17+
Condvar { inner: UnsafeCell::new(libc::PTHREAD_COND_INITIALIZER) }
18+
}
19+
20+
#[inline]
21+
fn raw(&self) -> *mut libc::pthread_cond_t {
22+
self.inner.get()
23+
}
24+
25+
/// # Safety
26+
/// `init` must have been called.
27+
#[inline]
28+
pub unsafe fn notify_one(self: Pin<&Self>) {
29+
let r = unsafe { libc::pthread_cond_signal(self.raw()) };
30+
debug_assert_eq!(r, 0);
31+
}
32+
33+
/// # Safety
34+
/// `init` must have been called.
35+
#[inline]
36+
pub unsafe fn notify_all(self: Pin<&Self>) {
37+
let r = unsafe { libc::pthread_cond_broadcast(self.raw()) };
38+
debug_assert_eq!(r, 0);
39+
}
40+
41+
/// # Safety
42+
/// * `init` must have been called.
43+
/// * `mutex` must be locked by the current thread.
44+
/// * This condition variable may only be used with the same mutex.
45+
#[inline]
46+
pub unsafe fn wait(self: Pin<&Self>, mutex: Pin<&Mutex>) {
47+
let r = unsafe { libc::pthread_cond_wait(self.raw(), mutex.raw()) };
48+
debug_assert_eq!(r, 0);
49+
}
50+
51+
/// # Safety
52+
/// * `init` must have been called.
53+
/// * `mutex` must be locked by the current thread.
54+
/// * This condition variable may only be used with the same mutex.
55+
pub unsafe fn wait_timeout(&self, mutex: Pin<&Mutex>, dur: Duration) -> bool {
56+
let mutex = mutex.raw();
57+
58+
// OSX implementation of `pthread_cond_timedwait` is buggy
59+
// with super long durations. When duration is greater than
60+
// 0x100_0000_0000_0000 seconds, `pthread_cond_timedwait`
61+
// in macOS Sierra returns error 316.
62+
//
63+
// This program demonstrates the issue:
64+
// https://gist.github.com/stepancheg/198db4623a20aad2ad7cddb8fda4a63c
65+
//
66+
// To work around this issue, the timeout is clamped to 1000 years.
67+
#[cfg(target_vendor = "apple")]
68+
let dur = Duration::min(dur, Duration::from_secs(1000 * 365 * 86400));
69+
70+
let timeout = Timespec::now(Self::CLOCK).checked_add_duration(&dur);
71+
72+
#[cfg(not(target_os = "nto"))]
73+
let timeout = timeout.and_then(|t| t.to_timespec()).unwrap_or(TIMESPEC_MAX);
74+
75+
#[cfg(target_os = "nto")]
76+
let timeout = timeout.and_then(|t| t.to_timespec_capped()).unwrap_or(TIMESPEC_MAX_CAPPED);
77+
78+
let r = unsafe { libc::pthread_cond_timedwait(self.raw(), mutex, &timeout) };
79+
assert!(r == libc::ETIMEDOUT || r == 0);
80+
r == 0
81+
}
82+
}
83+
84+
#[cfg(not(any(
85+
target_os = "android",
86+
target_vendor = "apple",
87+
target_os = "espidf",
88+
target_os = "horizon",
89+
target_os = "l4re",
90+
target_os = "redox",
91+
)))]
92+
impl Condvar {
93+
pub const PRECISE_TIMEOUT: bool = true;
94+
const CLOCK: libc::clockid_t = libc::CLOCK_MONOTONIC;
95+
96+
/// # Safety
97+
/// May only be called once.
98+
pub unsafe fn init(self: Pin<&mut Self>) {
99+
use crate::mem::MaybeUninit;
100+
101+
struct AttrGuard<'a>(pub &'a mut MaybeUninit<libc::pthread_condattr_t>);
102+
impl Drop for AttrGuard<'_> {
103+
fn drop(&mut self) {
104+
unsafe {
105+
let result = libc::pthread_condattr_destroy(self.0.as_mut_ptr());
106+
assert_eq!(result, 0);
107+
}
108+
}
109+
}
110+
111+
unsafe {
112+
let mut attr = MaybeUninit::<libc::pthread_condattr_t>::uninit();
113+
let r = libc::pthread_condattr_init(attr.as_mut_ptr());
114+
assert_eq!(r, 0);
115+
let attr = AttrGuard(&mut attr);
116+
let r = libc::pthread_condattr_setclock(attr.0.as_mut_ptr(), Self::CLOCK);
117+
assert_eq!(r, 0);
118+
let r = libc::pthread_cond_init(self.raw(), attr.0.as_ptr());
119+
assert_eq!(r, 0);
120+
}
121+
}
122+
}
123+
124+
// `pthread_condattr_setclock` is unfortunately not supported on these platforms.
125+
#[cfg(any(
126+
target_os = "android",
127+
target_vendor = "apple",
128+
target_os = "espidf",
129+
target_os = "horizon",
130+
target_os = "l4re",
131+
target_os = "redox",
132+
))]
133+
impl Condvar {
134+
pub const PRECISE_TIMEOUT: bool = false;
135+
const CLOCK: libc::clockid_t = libc::CLOCK_REALTIME;
136+
137+
/// # Safety
138+
/// May only be called once.
139+
pub unsafe fn init(self: Pin<&mut Self>) {
140+
if cfg!(any(target_os = "espidf", target_os = "horizon")) {
141+
// NOTE: ESP-IDF's PTHREAD_COND_INITIALIZER support is not released yet
142+
// So on that platform, init() should always be called.
143+
//
144+
// Similar story for the 3DS (horizon).
145+
let r = unsafe { libc::pthread_cond_init(self.raw(), crate::ptr::null()) };
146+
assert_eq!(r, 0);
147+
}
148+
}
149+
}
150+
151+
impl !Unpin for Condvar {}
152+
153+
unsafe impl Sync for Condvar {}
154+
unsafe impl Send for Condvar {}
155+
156+
impl Drop for Condvar {
157+
#[inline]
158+
fn drop(&mut self) {
159+
let r = unsafe { libc::pthread_cond_destroy(self.raw()) };
160+
if cfg!(target_os = "dragonfly") {
161+
// On DragonFly pthread_cond_destroy() returns EINVAL if called on
162+
// a condvar that was just initialized with
163+
// libc::PTHREAD_COND_INITIALIZER. Once it is used or
164+
// pthread_cond_init() is called, this behaviour no longer occurs.
165+
debug_assert!(r == 0 || r == libc::EINVAL);
166+
} else {
167+
debug_assert_eq!(r, 0);
168+
}
169+
}
170+
}

Diff for: library/std/src/sys/pal/unix/sync/mod.rs

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#![forbid(unsafe_op_in_unsafe_fn)]
2+
3+
mod condvar;
4+
mod mutex;
5+
6+
pub use condvar::Condvar;
7+
pub use mutex::Mutex;

Diff for: library/std/src/sys/pal/unix/sync/mutex.rs

+133
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
use super::super::cvt_nz;
2+
use crate::cell::UnsafeCell;
3+
use crate::io::Error;
4+
use crate::mem::MaybeUninit;
5+
use crate::pin::Pin;
6+
7+
pub struct Mutex {
8+
inner: UnsafeCell<libc::pthread_mutex_t>,
9+
}
10+
11+
impl Mutex {
12+
pub fn new() -> Mutex {
13+
Mutex { inner: UnsafeCell::new(libc::PTHREAD_MUTEX_INITIALIZER) }
14+
}
15+
16+
pub(super) fn raw(&self) -> *mut libc::pthread_mutex_t {
17+
self.inner.get()
18+
}
19+
20+
/// # Safety
21+
/// Must only be called once.
22+
pub unsafe fn init(self: Pin<&mut Self>) {
23+
// Issue #33770
24+
//
25+
// A pthread mutex initialized with PTHREAD_MUTEX_INITIALIZER will have
26+
// a type of PTHREAD_MUTEX_DEFAULT, which has undefined behavior if you
27+
// try to re-lock it from the same thread when you already hold a lock
28+
// (https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_init.html).
29+
// This is the case even if PTHREAD_MUTEX_DEFAULT == PTHREAD_MUTEX_NORMAL
30+
// (https://github.com/rust-lang/rust/issues/33770#issuecomment-220847521) -- in that
31+
// case, `pthread_mutexattr_settype(PTHREAD_MUTEX_DEFAULT)` will of course be the same
32+
// as setting it to `PTHREAD_MUTEX_NORMAL`, but not setting any mode will result in
33+
// a Mutex where re-locking is UB.
34+
//
35+
// In practice, glibc takes advantage of this undefined behavior to
36+
// implement hardware lock elision, which uses hardware transactional
37+
// memory to avoid acquiring the lock. While a transaction is in
38+
// progress, the lock appears to be unlocked. This isn't a problem for
39+
// other threads since the transactional memory will abort if a conflict
40+
// is detected, however no abort is generated when re-locking from the
41+
// same thread.
42+
//
43+
// Since locking the same mutex twice will result in two aliasing &mut
44+
// references, we instead create the mutex with type
45+
// PTHREAD_MUTEX_NORMAL which is guaranteed to deadlock if we try to
46+
// re-lock it from the same thread, thus avoiding undefined behavior.
47+
unsafe {
48+
let mut attr = MaybeUninit::<libc::pthread_mutexattr_t>::uninit();
49+
cvt_nz(libc::pthread_mutexattr_init(attr.as_mut_ptr())).unwrap();
50+
let attr = AttrGuard(&mut attr);
51+
cvt_nz(libc::pthread_mutexattr_settype(
52+
attr.0.as_mut_ptr(),
53+
libc::PTHREAD_MUTEX_NORMAL,
54+
))
55+
.unwrap();
56+
cvt_nz(libc::pthread_mutex_init(self.raw(), attr.0.as_ptr())).unwrap();
57+
}
58+
}
59+
60+
/// # Safety
61+
/// * If `init` was not called, reentrant locking causes undefined behaviour.
62+
/// * Destroying a locked mutex causes undefined behaviour.
63+
pub unsafe fn lock(self: Pin<&Self>) {
64+
#[cold]
65+
#[inline(never)]
66+
fn fail(r: i32) -> ! {
67+
let error = Error::from_raw_os_error(r);
68+
panic!("failed to lock mutex: {error}");
69+
}
70+
71+
let r = unsafe { libc::pthread_mutex_lock(self.raw()) };
72+
// As we set the mutex type to `PTHREAD_MUTEX_NORMAL` above, we expect
73+
// the lock call to never fail. Unfortunately however, some platforms
74+
// (Solaris) do not conform to the standard, and instead always provide
75+
// deadlock detection. How kind of them! Unfortunately that means that
76+
// we need to check the error code here. To save us from UB on other
77+
// less well-behaved platforms in the future, we do it even on "good"
78+
// platforms like macOS. See #120147 for more context.
79+
if r != 0 {
80+
fail(r)
81+
}
82+
}
83+
84+
/// # Safety
85+
/// * If `init` was not called, reentrant locking causes undefined behaviour.
86+
/// * Destroying a locked mutex causes undefined behaviour.
87+
pub unsafe fn try_lock(self: Pin<&Self>) -> bool {
88+
unsafe { libc::pthread_mutex_trylock(self.raw()) == 0 }
89+
}
90+
91+
/// # Safety
92+
/// The mutex must be locked by the current thread.
93+
pub unsafe fn unlock(self: Pin<&Self>) {
94+
let r = unsafe { libc::pthread_mutex_unlock(self.raw()) };
95+
debug_assert_eq!(r, 0);
96+
}
97+
}
98+
99+
impl !Unpin for Mutex {}
100+
101+
unsafe impl Send for Mutex {}
102+
unsafe impl Sync for Mutex {}
103+
104+
impl Drop for Mutex {
105+
fn drop(&mut self) {
106+
// SAFETY:
107+
// If `lock` or `init` was called, the mutex must have been pinned, so
108+
// it is still at the same location. Otherwise, `inner` must contain
109+
// `PTHREAD_MUTEX_INITIALIZER`, which is valid at all locations. Thus,
110+
// this call always destroys a valid mutex.
111+
let r = unsafe { libc::pthread_mutex_destroy(self.raw()) };
112+
if cfg!(target_os = "dragonfly") {
113+
// On DragonFly pthread_mutex_destroy() returns EINVAL if called on a
114+
// mutex that was just initialized with libc::PTHREAD_MUTEX_INITIALIZER.
115+
// Once it is used (locked/unlocked) or pthread_mutex_init() is called,
116+
// this behaviour no longer occurs.
117+
debug_assert!(r == 0 || r == libc::EINVAL);
118+
} else {
119+
debug_assert_eq!(r, 0);
120+
}
121+
}
122+
}
123+
124+
struct AttrGuard<'a>(pub &'a mut MaybeUninit<libc::pthread_mutexattr_t>);
125+
126+
impl Drop for AttrGuard<'_> {
127+
fn drop(&mut self) {
128+
unsafe {
129+
let result = libc::pthread_mutexattr_destroy(self.0.as_mut_ptr());
130+
assert_eq!(result, 0);
131+
}
132+
}
133+
}

0 commit comments

Comments
 (0)