Skip to content

Commit 528b37a

Browse files
committedOct 28, 2024··
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 a non-movable wrapper type for `pthread_mutex_t` and `pthread_condvar_t`.
1 parent 32b17d5 commit 528b37a

File tree

11 files changed

+463
-438
lines changed

11 files changed

+463
-438
lines changed
 

‎library/std/src/sys/pal/teeos/mod.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,14 @@ pub mod thread;
2727
#[path = "../unix/time.rs"]
2828
pub mod time;
2929

30+
#[path = "../unix/sync"]
31+
pub mod sync {
32+
mod condvar;
33+
mod mutex;
34+
pub use condvar::Condvar;
35+
pub use mutex::Mutex;
36+
}
37+
3038
use crate::io::ErrorKind;
3139

3240
pub fn abort_internal() -> ! {

‎library/std/src/sys/pal/unix/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ pub mod pipe;
2727
pub mod process;
2828
pub mod stack_overflow;
2929
pub mod stdio;
30+
pub mod sync;
3031
pub mod thread;
3132
pub mod thread_parking;
3233
pub mod time;
Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
use super::Mutex;
2+
use crate::cell::UnsafeCell;
3+
use crate::pin::Pin;
4+
#[cfg(not(target_os = "nto"))]
5+
use crate::sys::pal::time::TIMESPEC_MAX;
6+
#[cfg(target_os = "nto")]
7+
use crate::sys::pal::time::TIMESPEC_MAX_CAPPED;
8+
use crate::sys::pal::time::Timespec;
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+
target_os = "teeos",
92+
)))]
93+
impl Condvar {
94+
pub const PRECISE_TIMEOUT: bool = true;
95+
const CLOCK: libc::clockid_t = libc::CLOCK_MONOTONIC;
96+
97+
/// # Safety
98+
/// May only be called once.
99+
pub unsafe fn init(self: Pin<&mut Self>) {
100+
use crate::mem::MaybeUninit;
101+
102+
struct AttrGuard<'a>(pub &'a mut MaybeUninit<libc::pthread_condattr_t>);
103+
impl Drop for AttrGuard<'_> {
104+
fn drop(&mut self) {
105+
unsafe {
106+
let result = libc::pthread_condattr_destroy(self.0.as_mut_ptr());
107+
assert_eq!(result, 0);
108+
}
109+
}
110+
}
111+
112+
unsafe {
113+
let mut attr = MaybeUninit::<libc::pthread_condattr_t>::uninit();
114+
let r = libc::pthread_condattr_init(attr.as_mut_ptr());
115+
assert_eq!(r, 0);
116+
let attr = AttrGuard(&mut attr);
117+
let r = libc::pthread_condattr_setclock(attr.0.as_mut_ptr(), Self::CLOCK);
118+
assert_eq!(r, 0);
119+
let r = libc::pthread_cond_init(self.raw(), attr.0.as_ptr());
120+
assert_eq!(r, 0);
121+
}
122+
}
123+
}
124+
125+
// `pthread_condattr_setclock` is unfortunately not supported on these platforms.
126+
#[cfg(any(
127+
target_os = "android",
128+
target_vendor = "apple",
129+
target_os = "espidf",
130+
target_os = "horizon",
131+
target_os = "l4re",
132+
target_os = "redox",
133+
target_os = "teeos",
134+
))]
135+
impl Condvar {
136+
pub const PRECISE_TIMEOUT: bool = false;
137+
const CLOCK: libc::clockid_t = libc::CLOCK_REALTIME;
138+
139+
/// # Safety
140+
/// May only be called once.
141+
pub unsafe fn init(self: Pin<&mut Self>) {
142+
if cfg!(any(target_os = "espidf", target_os = "horizon", target_os = "teeos")) {
143+
// NOTE: ESP-IDF's PTHREAD_COND_INITIALIZER support is not released yet
144+
// So on that platform, init() should always be called.
145+
//
146+
// Similar story for the 3DS (horizon) and for TEEOS.
147+
let r = unsafe { libc::pthread_cond_init(self.raw(), crate::ptr::null()) };
148+
assert_eq!(r, 0);
149+
}
150+
}
151+
}
152+
153+
impl !Unpin for Condvar {}
154+
155+
unsafe impl Sync for Condvar {}
156+
unsafe impl Send for Condvar {}
157+
158+
impl Drop for Condvar {
159+
#[inline]
160+
fn drop(&mut self) {
161+
let r = unsafe { libc::pthread_cond_destroy(self.raw()) };
162+
if cfg!(target_os = "dragonfly") {
163+
// On DragonFly pthread_cond_destroy() returns EINVAL if called on
164+
// a condvar that was just initialized with
165+
// libc::PTHREAD_COND_INITIALIZER. Once it is used or
166+
// pthread_cond_init() is called, this behaviour no longer occurs.
167+
debug_assert!(r == 0 || r == libc::EINVAL);
168+
} else {
169+
debug_assert_eq!(r, 0);
170+
}
171+
}
172+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#![cfg(not(any(
2+
target_os = "linux",
3+
target_os = "android",
4+
all(target_os = "emscripten", target_feature = "atomics"),
5+
target_os = "freebsd",
6+
target_os = "openbsd",
7+
target_os = "dragonfly",
8+
target_os = "fuchsia",
9+
)))]
10+
#![forbid(unsafe_op_in_unsafe_fn)]
11+
12+
mod condvar;
13+
mod mutex;
14+
15+
pub use condvar::Condvar;
16+
pub use mutex::Mutex;
Lines changed: 133 additions & 0 deletions
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+
}
Lines changed: 51 additions & 159 deletions
Original file line numberDiff line numberDiff line change
@@ -1,196 +1,88 @@
1-
use crate::cell::UnsafeCell;
1+
#![forbid(unsafe_op_in_unsafe_fn)]
2+
3+
use crate::pin::Pin;
24
use crate::ptr;
3-
use crate::sync::atomic::AtomicPtr;
5+
use crate::sync::atomic::AtomicUsize;
46
use crate::sync::atomic::Ordering::Relaxed;
7+
use crate::sys::pal::sync as pal;
58
use crate::sys::sync::{Mutex, OnceBox};
6-
#[cfg(not(target_os = "nto"))]
7-
use crate::sys::time::TIMESPEC_MAX;
8-
#[cfg(target_os = "nto")]
9-
use crate::sys::time::TIMESPEC_MAX_CAPPED;
10-
use crate::time::Duration;
11-
12-
struct AllocatedCondvar(UnsafeCell<libc::pthread_cond_t>);
9+
use crate::time::{Duration, Instant};
1310

1411
pub struct Condvar {
15-
inner: OnceBox<AllocatedCondvar>,
16-
mutex: AtomicPtr<libc::pthread_mutex_t>,
17-
}
18-
19-
unsafe impl Send for AllocatedCondvar {}
20-
unsafe impl Sync for AllocatedCondvar {}
21-
22-
impl AllocatedCondvar {
23-
fn new() -> Box<Self> {
24-
let condvar = Box::new(AllocatedCondvar(UnsafeCell::new(libc::PTHREAD_COND_INITIALIZER)));
25-
26-
cfg_if::cfg_if! {
27-
if #[cfg(any(
28-
target_os = "l4re",
29-
target_os = "android",
30-
target_os = "redox",
31-
target_vendor = "apple",
32-
))] {
33-
// `pthread_condattr_setclock` is unfortunately not supported on these platforms.
34-
} else if #[cfg(any(target_os = "espidf", target_os = "horizon", target_os = "teeos"))] {
35-
// NOTE: ESP-IDF's PTHREAD_COND_INITIALIZER support is not released yet
36-
// So on that platform, init() should always be called
37-
// Moreover, that platform does not have pthread_condattr_setclock support,
38-
// hence that initialization should be skipped as well
39-
//
40-
// Similar story for the 3DS (horizon).
41-
let r = unsafe { libc::pthread_cond_init(condvar.0.get(), crate::ptr::null()) };
42-
assert_eq!(r, 0);
43-
} else {
44-
use crate::mem::MaybeUninit;
45-
let mut attr = MaybeUninit::<libc::pthread_condattr_t>::uninit();
46-
let r = unsafe { libc::pthread_condattr_init(attr.as_mut_ptr()) };
47-
assert_eq!(r, 0);
48-
let r = unsafe { libc::pthread_condattr_setclock(attr.as_mut_ptr(), libc::CLOCK_MONOTONIC) };
49-
assert_eq!(r, 0);
50-
let r = unsafe { libc::pthread_cond_init(condvar.0.get(), attr.as_ptr()) };
51-
assert_eq!(r, 0);
52-
let r = unsafe { libc::pthread_condattr_destroy(attr.as_mut_ptr()) };
53-
assert_eq!(r, 0);
54-
}
55-
}
56-
57-
condvar
58-
}
59-
}
60-
61-
impl Drop for AllocatedCondvar {
62-
#[inline]
63-
fn drop(&mut self) {
64-
let r = unsafe { libc::pthread_cond_destroy(self.0.get()) };
65-
if cfg!(target_os = "dragonfly") {
66-
// On DragonFly pthread_cond_destroy() returns EINVAL if called on
67-
// a condvar that was just initialized with
68-
// libc::PTHREAD_COND_INITIALIZER. Once it is used or
69-
// pthread_cond_init() is called, this behavior no longer occurs.
70-
debug_assert!(r == 0 || r == libc::EINVAL);
71-
} else {
72-
debug_assert_eq!(r, 0);
73-
}
74-
}
12+
cvar: OnceBox<pal::Condvar>,
13+
mutex: AtomicUsize,
7514
}
7615

7716
impl Condvar {
7817
pub const fn new() -> Condvar {
79-
Condvar { inner: OnceBox::new(), mutex: AtomicPtr::new(ptr::null_mut()) }
18+
Condvar { cvar: OnceBox::new(), mutex: AtomicUsize::new(0) }
8019
}
8120

82-
fn get(&self) -> *mut libc::pthread_cond_t {
83-
self.inner.get_or_init(AllocatedCondvar::new).0.get()
21+
#[inline]
22+
fn get(&self) -> Pin<&pal::Condvar> {
23+
self.cvar.get_or_init(|| {
24+
let mut cvar = Box::pin(pal::Condvar::new());
25+
// SAFETY: we only call `init` once, namely here.
26+
unsafe { cvar.as_mut().init() };
27+
cvar
28+
})
8429
}
8530

8631
#[inline]
87-
fn verify(&self, mutex: *mut libc::pthread_mutex_t) {
88-
// Relaxed is okay here because we never read through `self.addr`, and only use it to
32+
fn verify(&self, mutex: Pin<&pal::Mutex>) {
33+
let addr = ptr::from_ref::<pal::Mutex>(&mutex).addr();
34+
// Relaxed is okay here because we never read through `self.mutex`, and only use it to
8935
// compare addresses.
90-
match self.mutex.compare_exchange(ptr::null_mut(), mutex, Relaxed, Relaxed) {
91-
Ok(_) => {} // Stored the address
92-
Err(n) if n == mutex => {} // Lost a race to store the same address
36+
match self.mutex.compare_exchange(0, addr, Relaxed, Relaxed) {
37+
Ok(_) => {} // Stored the address
38+
Err(n) if n == addr => {} // Lost a race to store the same address
9339
_ => panic!("attempted to use a condition variable with two mutexes"),
9440
}
9541
}
9642

9743
#[inline]
9844
pub fn notify_one(&self) {
99-
let r = unsafe { libc::pthread_cond_signal(self.get()) };
100-
debug_assert_eq!(r, 0);
45+
// SAFETY: we called `init` above.
46+
unsafe { self.get().notify_one() }
10147
}
10248

10349
#[inline]
10450
pub fn notify_all(&self) {
105-
let r = unsafe { libc::pthread_cond_broadcast(self.get()) };
106-
debug_assert_eq!(r, 0);
51+
// SAFETY: we called `init` above.
52+
unsafe { self.get().notify_all() }
10753
}
10854

10955
#[inline]
11056
pub unsafe fn wait(&self, mutex: &Mutex) {
111-
let mutex = mutex.get_assert_locked();
57+
// SAFETY: the caller guarantees that the lock is owned, thus the mutex
58+
// must have been initialized already.
59+
let mutex = unsafe { mutex.pal.get_unchecked() };
11260
self.verify(mutex);
113-
let r = libc::pthread_cond_wait(self.get(), mutex);
114-
debug_assert_eq!(r, 0);
61+
// SAFETY: we called `init` above, we verified that this condition
62+
// variable is only used with `mutex` and the caller guarantees that
63+
// `mutex` is locked by the current thread.
64+
unsafe { self.get().wait(mutex) }
11565
}
11666

117-
// This implementation is used on systems that support pthread_condattr_setclock
118-
// where we configure condition variable to use monotonic clock (instead of
119-
// default system clock). This approach avoids all problems that result
120-
// from changes made to the system time.
121-
#[cfg(not(any(
122-
target_os = "android",
123-
target_os = "espidf",
124-
target_os = "horizon",
125-
target_vendor = "apple",
126-
)))]
12767
pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
128-
use crate::sys::time::Timespec;
129-
130-
let mutex = mutex.get_assert_locked();
68+
// SAFETY: the caller guarantees that the lock is owned, thus the mutex
69+
// must have been initialized already.
70+
let mutex = unsafe { mutex.pal.get_unchecked() };
13171
self.verify(mutex);
13272

133-
#[cfg(not(target_os = "nto"))]
134-
let timeout = Timespec::now(libc::CLOCK_MONOTONIC)
135-
.checked_add_duration(&dur)
136-
.and_then(|t| t.to_timespec())
137-
.unwrap_or(TIMESPEC_MAX);
138-
139-
#[cfg(target_os = "nto")]
140-
let timeout = Timespec::now(libc::CLOCK_MONOTONIC)
141-
.checked_add_duration(&dur)
142-
.and_then(|t| t.to_timespec_capped())
143-
.unwrap_or(TIMESPEC_MAX_CAPPED);
144-
145-
let r = libc::pthread_cond_timedwait(self.get(), mutex, &timeout);
146-
assert!(r == libc::ETIMEDOUT || r == 0);
147-
r == 0
148-
}
149-
150-
// This implementation is modeled after libcxx's condition_variable
151-
// https://github.com/llvm-mirror/libcxx/blob/release_35/src/condition_variable.cpp#L46
152-
// https://github.com/llvm-mirror/libcxx/blob/release_35/include/__mutex_base#L367
153-
#[cfg(any(
154-
target_os = "android",
155-
target_os = "espidf",
156-
target_os = "horizon",
157-
target_vendor = "apple",
158-
))]
159-
pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
160-
use crate::sys::time::SystemTime;
161-
use crate::time::Instant;
162-
163-
let mutex = mutex.get_assert_locked();
164-
self.verify(mutex);
165-
166-
// OSX implementation of `pthread_cond_timedwait` is buggy
167-
// with super long durations. When duration is greater than
168-
// 0x100_0000_0000_0000 seconds, `pthread_cond_timedwait`
169-
// in macOS Sierra returns error 316.
170-
//
171-
// This program demonstrates the issue:
172-
// https://gist.github.com/stepancheg/198db4623a20aad2ad7cddb8fda4a63c
173-
//
174-
// To work around this issue, and possible bugs of other OSes, timeout
175-
// is clamped to 1000 years, which is allowable per the API of `wait_timeout`
176-
// because of spurious wakeups.
177-
let dur = Duration::min(dur, Duration::from_secs(1000 * 365 * 86400));
178-
179-
// pthread_cond_timedwait uses system time, but we want to report timeout
180-
// based on stable time.
181-
let now = Instant::now();
182-
183-
let timeout = SystemTime::now()
184-
.t
185-
.checked_add_duration(&dur)
186-
.and_then(|t| t.to_timespec())
187-
.unwrap_or(TIMESPEC_MAX);
188-
189-
let r = libc::pthread_cond_timedwait(self.get(), mutex, &timeout);
190-
debug_assert!(r == libc::ETIMEDOUT || r == 0);
191-
192-
// ETIMEDOUT is not a totally reliable method of determining timeout due
193-
// to clock shifts, so do the check ourselves
194-
now.elapsed() < dur
73+
if pal::Condvar::PRECISE_TIMEOUT {
74+
// SAFETY: we called `init` above, we verified that this condition
75+
// variable is only used with `mutex` and the caller guarantees that
76+
// `mutex` is locked by the current thread.
77+
unsafe { self.get().wait_timeout(mutex, dur) }
78+
} else {
79+
// Timeout reports are not reliable, so do the check ourselves.
80+
let now = Instant::now();
81+
// SAFETY: we called `init` above, we verified that this condition
82+
// variable is only used with `mutex` and the caller guarantees that
83+
// `mutex` is locked by the current thread.
84+
let woken = unsafe { self.get().wait_timeout(mutex, dur) };
85+
woken || now.elapsed() < dur
86+
}
19587
}
19688
}

‎library/std/src/sys/sync/condvar/sgx.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,17 +13,19 @@ impl Condvar {
1313
}
1414

1515
fn get(&self) -> &SpinMutex<WaitVariable<()>> {
16-
self.inner.get_or_init(|| Box::new(SpinMutex::new(WaitVariable::new(()))))
16+
self.inner.get_or_init(|| Box::pin(SpinMutex::new(WaitVariable::new(())))).get_ref()
1717
}
1818

1919
#[inline]
2020
pub fn notify_one(&self) {
21-
let _ = WaitQueue::notify_one(self.get().lock());
21+
let guard = self.get().lock();
22+
let _ = WaitQueue::notify_one(guard);
2223
}
2324

2425
#[inline]
2526
pub fn notify_all(&self) {
26-
let _ = WaitQueue::notify_all(self.get().lock());
27+
let guard = self.get().lock();
28+
let _ = WaitQueue::notify_all(guard);
2729
}
2830

2931
pub unsafe fn wait(&self, mutex: &Mutex) {
Lines changed: 30 additions & 127 deletions
Original file line numberDiff line numberDiff line change
@@ -1,163 +1,66 @@
1-
use crate::cell::UnsafeCell;
2-
use crate::io::Error;
3-
use crate::mem::{MaybeUninit, forget};
4-
use crate::sys::cvt_nz;
5-
use crate::sys::sync::OnceBox;
1+
#![forbid(unsafe_op_in_unsafe_fn)]
62

7-
struct AllocatedMutex(UnsafeCell<libc::pthread_mutex_t>);
3+
use crate::mem::forget;
4+
use crate::pin::Pin;
5+
use crate::sys::pal::sync as pal;
6+
use crate::sys::sync::OnceBox;
87

98
pub struct Mutex {
10-
inner: OnceBox<AllocatedMutex>,
11-
}
12-
13-
unsafe impl Send for AllocatedMutex {}
14-
unsafe impl Sync for AllocatedMutex {}
15-
16-
impl AllocatedMutex {
17-
fn new() -> Box<Self> {
18-
let mutex = Box::new(AllocatedMutex(UnsafeCell::new(libc::PTHREAD_MUTEX_INITIALIZER)));
19-
20-
// Issue #33770
21-
//
22-
// A pthread mutex initialized with PTHREAD_MUTEX_INITIALIZER will have
23-
// a type of PTHREAD_MUTEX_DEFAULT, which has undefined behavior if you
24-
// try to re-lock it from the same thread when you already hold a lock
25-
// (https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_init.html).
26-
// This is the case even if PTHREAD_MUTEX_DEFAULT == PTHREAD_MUTEX_NORMAL
27-
// (https://github.com/rust-lang/rust/issues/33770#issuecomment-220847521) -- in that
28-
// case, `pthread_mutexattr_settype(PTHREAD_MUTEX_DEFAULT)` will of course be the same
29-
// as setting it to `PTHREAD_MUTEX_NORMAL`, but not setting any mode will result in
30-
// a Mutex where re-locking is UB.
31-
//
32-
// In practice, glibc takes advantage of this undefined behavior to
33-
// implement hardware lock elision, which uses hardware transactional
34-
// memory to avoid acquiring the lock. While a transaction is in
35-
// progress, the lock appears to be unlocked. This isn't a problem for
36-
// other threads since the transactional memory will abort if a conflict
37-
// is detected, however no abort is generated when re-locking from the
38-
// same thread.
39-
//
40-
// Since locking the same mutex twice will result in two aliasing &mut
41-
// references, we instead create the mutex with type
42-
// PTHREAD_MUTEX_NORMAL which is guaranteed to deadlock if we try to
43-
// re-lock it from the same thread, thus avoiding undefined behavior.
44-
unsafe {
45-
let mut attr = MaybeUninit::<libc::pthread_mutexattr_t>::uninit();
46-
cvt_nz(libc::pthread_mutexattr_init(attr.as_mut_ptr())).unwrap();
47-
let attr = PthreadMutexAttr(&mut attr);
48-
cvt_nz(libc::pthread_mutexattr_settype(
49-
attr.0.as_mut_ptr(),
50-
libc::PTHREAD_MUTEX_NORMAL,
51-
))
52-
.unwrap();
53-
cvt_nz(libc::pthread_mutex_init(mutex.0.get(), attr.0.as_ptr())).unwrap();
54-
}
55-
56-
mutex
57-
}
58-
}
59-
60-
impl Drop for AllocatedMutex {
61-
#[inline]
62-
fn drop(&mut self) {
63-
let r = unsafe { libc::pthread_mutex_destroy(self.0.get()) };
64-
if cfg!(target_os = "dragonfly") {
65-
// On DragonFly pthread_mutex_destroy() returns EINVAL if called on a
66-
// mutex that was just initialized with libc::PTHREAD_MUTEX_INITIALIZER.
67-
// Once it is used (locked/unlocked) or pthread_mutex_init() is called,
68-
// this behavior no longer occurs.
69-
debug_assert!(r == 0 || r == libc::EINVAL);
70-
} else {
71-
debug_assert_eq!(r, 0);
72-
}
73-
}
9+
pub pal: OnceBox<pal::Mutex>,
7410
}
7511

7612
impl Mutex {
7713
#[inline]
7814
pub const fn new() -> Mutex {
79-
Mutex { inner: OnceBox::new() }
15+
Mutex { pal: OnceBox::new() }
8016
}
8117

82-
/// Gets access to the pthread mutex under the assumption that the mutex is
83-
/// locked.
84-
///
85-
/// This allows skipping the initialization check, as the mutex can only be
86-
/// locked if it is already initialized, and allows relaxing the ordering
87-
/// on the pointer load, since the allocation cannot have been modified
88-
/// since the `lock` and the lock must have occurred on the current thread.
89-
///
90-
/// # Safety
91-
/// Causes undefined behavior if the mutex is not locked.
9218
#[inline]
93-
pub(crate) unsafe fn get_assert_locked(&self) -> *mut libc::pthread_mutex_t {
94-
unsafe { self.inner.get_unchecked().0.get() }
95-
}
96-
97-
#[inline]
98-
fn get(&self) -> *mut libc::pthread_mutex_t {
99-
// If initialization fails, the mutex is destroyed. This is always sound,
100-
// however, as the mutex cannot have been locked yet.
101-
self.inner.get_or_init(AllocatedMutex::new).0.get()
19+
fn get(&self) -> Pin<&pal::Mutex> {
20+
// If the initialization race is lost, the new mutex is destroyed.
21+
// This is sound however, as it cannot have been locked.
22+
self.pal.get_or_init(|| {
23+
let mut pal = Box::pin(pal::Mutex::new());
24+
// SAFETY: we only call `init` once, namely here.
25+
unsafe { pal.as_mut().init() };
26+
pal
27+
})
10228
}
10329

10430
#[inline]
10531
pub fn lock(&self) {
106-
#[cold]
107-
#[inline(never)]
108-
fn fail(r: i32) -> ! {
109-
let error = Error::from_raw_os_error(r);
110-
panic!("failed to lock mutex: {error}");
111-
}
112-
113-
let r = unsafe { libc::pthread_mutex_lock(self.get()) };
114-
// As we set the mutex type to `PTHREAD_MUTEX_NORMAL` above, we expect
115-
// the lock call to never fail. Unfortunately however, some platforms
116-
// (Solaris) do not conform to the standard, and instead always provide
117-
// deadlock detection. How kind of them! Unfortunately that means that
118-
// we need to check the error code here. To save us from UB on other
119-
// less well-behaved platforms in the future, we do it even on "good"
120-
// platforms like macOS. See #120147 for more context.
121-
if r != 0 {
122-
fail(r)
123-
}
32+
// SAFETY: we call `init` above, therefore reentrant locking is safe.
33+
// In `drop` we ensure that the mutex is not destroyed while locked.
34+
unsafe { self.get().lock() }
12435
}
12536

12637
#[inline]
12738
pub unsafe fn unlock(&self) {
128-
let r = libc::pthread_mutex_unlock(self.get_assert_locked());
129-
debug_assert_eq!(r, 0);
39+
// SAFETY: the mutex can only be locked if it is already initialized
40+
// and we observed this initialization since we observed the locking.
41+
unsafe { self.pal.get_unchecked().unlock() }
13042
}
13143

13244
#[inline]
13345
pub fn try_lock(&self) -> bool {
134-
unsafe { libc::pthread_mutex_trylock(self.get()) == 0 }
46+
// SAFETY: we call `init` above, therefore reentrant locking is safe.
47+
// In `drop` we ensure that the mutex is not destroyed while locked.
48+
unsafe { self.get().try_lock() }
13549
}
13650
}
13751

13852
impl Drop for Mutex {
13953
fn drop(&mut self) {
140-
let Some(mutex) = self.inner.take() else { return };
54+
let Some(pal) = self.pal.take() else { return };
14155
// We're not allowed to pthread_mutex_destroy a locked mutex,
14256
// so check first if it's unlocked.
143-
if unsafe { libc::pthread_mutex_trylock(mutex.0.get()) == 0 } {
144-
unsafe { libc::pthread_mutex_unlock(mutex.0.get()) };
145-
drop(mutex);
57+
if unsafe { pal.as_ref().try_lock() } {
58+
unsafe { pal.as_ref().unlock() };
59+
drop(pal)
14660
} else {
14761
// The mutex is locked. This happens if a MutexGuard is leaked.
14862
// In this case, we just leak the Mutex too.
149-
forget(mutex);
150-
}
151-
}
152-
}
153-
154-
pub(super) struct PthreadMutexAttr<'a>(pub &'a mut MaybeUninit<libc::pthread_mutexattr_t>);
155-
156-
impl Drop for PthreadMutexAttr<'_> {
157-
fn drop(&mut self) {
158-
unsafe {
159-
let result = libc::pthread_mutexattr_destroy(self.0.as_mut_ptr());
160-
debug_assert_eq!(result, 0);
63+
forget(pal)
16164
}
16265
}
16366
}

‎library/std/src/sys/sync/mutex/sgx.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ impl Mutex {
1313
}
1414

1515
fn get(&self) -> &SpinMutex<WaitVariable<bool>> {
16-
self.inner.get_or_init(|| Box::new(SpinMutex::new(WaitVariable::new(false))))
16+
self.inner.get_or_init(|| Box::pin(SpinMutex::new(WaitVariable::new(false)))).get_ref()
1717
}
1818

1919
#[inline]
@@ -33,7 +33,7 @@ impl Mutex {
3333
pub unsafe fn unlock(&self) {
3434
// SAFETY: the mutex was locked by the current thread, so it has been
3535
// initialized already.
36-
let guard = unsafe { self.inner.get_unchecked().lock() };
36+
let guard = unsafe { self.inner.get_unchecked().get_ref().lock() };
3737
if let Err(mut guard) = WaitQueue::notify_one(guard) {
3838
// No other waiters, unlock
3939
*guard.lock_var_mut() = false;

‎library/std/src/sys/sync/once_box.rs

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
#![allow(dead_code)] // Only used on some platforms.
77

88
use crate::mem::replace;
9+
use crate::pin::Pin;
910
use crate::ptr::null_mut;
1011
use crate::sync::atomic::AtomicPtr;
1112
use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release};
@@ -27,46 +28,46 @@ impl<T> OnceBox<T> {
2728
/// pointer load in this function can be performed with relaxed ordering,
2829
/// potentially allowing the optimizer to turn code like this:
2930
/// ```rust, ignore
30-
/// once_box.get_or_init(|| Box::new(42));
31+
/// once_box.get_or_init(|| Box::pin(42));
3132
/// unsafe { once_box.get_unchecked() }
3233
/// ```
3334
/// into
3435
/// ```rust, ignore
35-
/// once_box.get_or_init(|| Box::new(42))
36+
/// once_box.get_or_init(|| Box::pin(42))
3637
/// ```
3738
///
3839
/// # Safety
3940
/// This causes undefined behavior if the assumption above is violated.
4041
#[inline]
41-
pub unsafe fn get_unchecked(&self) -> &T {
42-
unsafe { &*self.ptr.load(Relaxed) }
42+
pub unsafe fn get_unchecked(&self) -> Pin<&T> {
43+
unsafe { Pin::new_unchecked(&*self.ptr.load(Relaxed)) }
4344
}
4445

4546
#[inline]
46-
pub fn get_or_init(&self, f: impl FnOnce() -> Box<T>) -> &T {
47+
pub fn get_or_init(&self, f: impl FnOnce() -> Pin<Box<T>>) -> Pin<&T> {
4748
let ptr = self.ptr.load(Acquire);
4849
match unsafe { ptr.as_ref() } {
49-
Some(val) => val,
50+
Some(val) => unsafe { Pin::new_unchecked(val) },
5051
None => self.initialize(f),
5152
}
5253
}
5354

5455
#[inline]
55-
pub fn take(&mut self) -> Option<Box<T>> {
56+
pub fn take(&mut self) -> Option<Pin<Box<T>>> {
5657
let ptr = replace(self.ptr.get_mut(), null_mut());
57-
if !ptr.is_null() { Some(unsafe { Box::from_raw(ptr) }) } else { None }
58+
if !ptr.is_null() { Some(unsafe { Pin::new_unchecked(Box::from_raw(ptr)) }) } else { None }
5859
}
5960

6061
#[cold]
61-
fn initialize(&self, f: impl FnOnce() -> Box<T>) -> &T {
62-
let new_ptr = Box::into_raw(f());
62+
fn initialize(&self, f: impl FnOnce() -> Pin<Box<T>>) -> Pin<&T> {
63+
let new_ptr = Box::into_raw(unsafe { Pin::into_inner_unchecked(f()) });
6364
match self.ptr.compare_exchange(null_mut(), new_ptr, Release, Acquire) {
64-
Ok(_) => unsafe { &*new_ptr },
65+
Ok(_) => unsafe { Pin::new_unchecked(&*new_ptr) },
6566
Err(ptr) => {
6667
// Lost the race to another thread.
6768
// Drop the value we created, and use the one from the other thread instead.
6869
drop(unsafe { Box::from_raw(new_ptr) });
69-
unsafe { &*ptr }
70+
unsafe { Pin::new_unchecked(&*ptr) }
7071
}
7172
}
7273
}
Lines changed: 32 additions & 135 deletions
Original file line numberDiff line numberDiff line change
@@ -1,93 +1,19 @@
11
//! Thread parking without `futex` using the `pthread` synchronization primitives.
22
3-
use crate::cell::UnsafeCell;
4-
use crate::marker::PhantomPinned;
53
use crate::pin::Pin;
64
use crate::sync::atomic::AtomicUsize;
75
use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release};
8-
#[cfg(not(target_os = "nto"))]
9-
use crate::sys::time::TIMESPEC_MAX;
10-
#[cfg(target_os = "nto")]
11-
use crate::sys::time::TIMESPEC_MAX_CAPPED;
6+
use crate::sys::pal::sync::{Condvar, Mutex};
127
use crate::time::Duration;
138

149
const EMPTY: usize = 0;
1510
const PARKED: usize = 1;
1611
const NOTIFIED: usize = 2;
1712

18-
unsafe fn lock(lock: *mut libc::pthread_mutex_t) {
19-
let r = libc::pthread_mutex_lock(lock);
20-
debug_assert_eq!(r, 0);
21-
}
22-
23-
unsafe fn unlock(lock: *mut libc::pthread_mutex_t) {
24-
let r = libc::pthread_mutex_unlock(lock);
25-
debug_assert_eq!(r, 0);
26-
}
27-
28-
unsafe fn notify_one(cond: *mut libc::pthread_cond_t) {
29-
let r = libc::pthread_cond_signal(cond);
30-
debug_assert_eq!(r, 0);
31-
}
32-
33-
unsafe fn wait(cond: *mut libc::pthread_cond_t, lock: *mut libc::pthread_mutex_t) {
34-
let r = libc::pthread_cond_wait(cond, lock);
35-
debug_assert_eq!(r, 0);
36-
}
37-
38-
unsafe fn wait_timeout(
39-
cond: *mut libc::pthread_cond_t,
40-
lock: *mut libc::pthread_mutex_t,
41-
dur: Duration,
42-
) {
43-
// Use the system clock on systems that do not support pthread_condattr_setclock.
44-
// This unfortunately results in problems when the system time changes.
45-
#[cfg(any(target_os = "espidf", target_os = "horizon", target_vendor = "apple"))]
46-
let (now, dur) = {
47-
use crate::cmp::min;
48-
use crate::sys::time::SystemTime;
49-
50-
// OSX implementation of `pthread_cond_timedwait` is buggy
51-
// with super long durations. When duration is greater than
52-
// 0x100_0000_0000_0000 seconds, `pthread_cond_timedwait`
53-
// in macOS Sierra return error 316.
54-
//
55-
// This program demonstrates the issue:
56-
// https://gist.github.com/stepancheg/198db4623a20aad2ad7cddb8fda4a63c
57-
//
58-
// To work around this issue, and possible bugs of other OSes, timeout
59-
// is clamped to 1000 years, which is allowable per the API of `park_timeout`
60-
// because of spurious wakeups.
61-
let dur = min(dur, Duration::from_secs(1000 * 365 * 86400));
62-
let now = SystemTime::now().t;
63-
(now, dur)
64-
};
65-
// Use the monotonic clock on other systems.
66-
#[cfg(not(any(target_os = "espidf", target_os = "horizon", target_vendor = "apple")))]
67-
let (now, dur) = {
68-
use crate::sys::time::Timespec;
69-
70-
(Timespec::now(libc::CLOCK_MONOTONIC), dur)
71-
};
72-
73-
#[cfg(not(target_os = "nto"))]
74-
let timeout =
75-
now.checked_add_duration(&dur).and_then(|t| t.to_timespec()).unwrap_or(TIMESPEC_MAX);
76-
#[cfg(target_os = "nto")]
77-
let timeout = now
78-
.checked_add_duration(&dur)
79-
.and_then(|t| t.to_timespec_capped())
80-
.unwrap_or(TIMESPEC_MAX_CAPPED);
81-
let r = libc::pthread_cond_timedwait(cond, lock, &timeout);
82-
debug_assert!(r == libc::ETIMEDOUT || r == 0);
83-
}
84-
8513
pub struct Parker {
8614
state: AtomicUsize,
87-
lock: UnsafeCell<libc::pthread_mutex_t>,
88-
cvar: UnsafeCell<libc::pthread_cond_t>,
89-
// The `pthread` primitives require a stable address, so make this struct `!Unpin`.
90-
_pinned: PhantomPinned,
15+
lock: Mutex,
16+
cvar: Condvar,
9117
}
9218

9319
impl Parker {
@@ -96,38 +22,21 @@ impl Parker {
9622
/// # Safety
9723
/// The constructed parker must never be moved.
9824
pub unsafe fn new_in_place(parker: *mut Parker) {
99-
// Use the default mutex implementation to allow for simpler initialization.
100-
// This could lead to undefined behavior when deadlocking. This is avoided
101-
// by not deadlocking. Note in particular the unlocking operation before any
102-
// panic, as code after the panic could try to park again.
103-
(&raw mut (*parker).state).write(AtomicUsize::new(EMPTY));
104-
(&raw mut (*parker).lock).write(UnsafeCell::new(libc::PTHREAD_MUTEX_INITIALIZER));
25+
parker.write(Parker {
26+
state: AtomicUsize::new(EMPTY),
27+
lock: Mutex::new(),
28+
cvar: Condvar::new(),
29+
});
10530

106-
cfg_if::cfg_if! {
107-
if #[cfg(any(
108-
target_os = "l4re",
109-
target_os = "android",
110-
target_os = "redox",
111-
target_os = "vita",
112-
target_vendor = "apple",
113-
))] {
114-
(&raw mut (*parker).cvar).write(UnsafeCell::new(libc::PTHREAD_COND_INITIALIZER));
115-
} else if #[cfg(any(target_os = "espidf", target_os = "horizon"))] {
116-
let r = libc::pthread_cond_init((&raw mut (*parker).cvar).cast(), crate::ptr::null());
117-
assert_eq!(r, 0);
118-
} else {
119-
use crate::mem::MaybeUninit;
120-
let mut attr = MaybeUninit::<libc::pthread_condattr_t>::uninit();
121-
let r = libc::pthread_condattr_init(attr.as_mut_ptr());
122-
assert_eq!(r, 0);
123-
let r = libc::pthread_condattr_setclock(attr.as_mut_ptr(), libc::CLOCK_MONOTONIC);
124-
assert_eq!(r, 0);
125-
let r = libc::pthread_cond_init((&raw mut (*parker).cvar).cast(), attr.as_ptr());
126-
assert_eq!(r, 0);
127-
let r = libc::pthread_condattr_destroy(attr.as_mut_ptr());
128-
assert_eq!(r, 0);
129-
}
130-
}
31+
Pin::new_unchecked(&mut (*parker).cvar).init();
32+
}
33+
34+
fn lock(self: Pin<&Self>) -> Pin<&Mutex> {
35+
unsafe { self.map_unchecked(|p| &p.lock) }
36+
}
37+
38+
fn cvar(self: Pin<&Self>) -> Pin<&Condvar> {
39+
unsafe { self.map_unchecked(|p| &p.cvar) }
13140
}
13241

13342
// This implementation doesn't require `unsafe`, but other implementations
@@ -142,7 +51,7 @@ impl Parker {
14251
}
14352

14453
// Otherwise we need to coordinate going to sleep
145-
lock(self.lock.get());
54+
self.lock().lock();
14655
match self.state.compare_exchange(EMPTY, PARKED, Relaxed, Relaxed) {
14756
Ok(_) => {}
14857
Err(NOTIFIED) => {
@@ -154,28 +63,28 @@ impl Parker {
15463
// read from the write it made to `state`.
15564
let old = self.state.swap(EMPTY, Acquire);
15665

157-
unlock(self.lock.get());
66+
self.lock().unlock();
15867

15968
assert_eq!(old, NOTIFIED, "park state changed unexpectedly");
16069
return;
16170
} // should consume this notification, so prohibit spurious wakeups in next park.
16271
Err(_) => {
163-
unlock(self.lock.get());
72+
self.lock().unlock();
16473

16574
panic!("inconsistent park state")
16675
}
16776
}
16877

16978
loop {
170-
wait(self.cvar.get(), self.lock.get());
79+
self.cvar().wait(self.lock());
17180

17281
match self.state.compare_exchange(NOTIFIED, EMPTY, Acquire, Relaxed) {
17382
Ok(_) => break, // got a notification
17483
Err(_) => {} // spurious wakeup, go back to sleep
17584
}
17685
}
17786

178-
unlock(self.lock.get());
87+
self.lock().unlock();
17988
}
18089

18190
// This implementation doesn't require `unsafe`, but other implementations
@@ -189,19 +98,19 @@ impl Parker {
18998
return;
19099
}
191100

192-
lock(self.lock.get());
101+
self.lock().lock();
193102
match self.state.compare_exchange(EMPTY, PARKED, Relaxed, Relaxed) {
194103
Ok(_) => {}
195104
Err(NOTIFIED) => {
196105
// We must read again here, see `park`.
197106
let old = self.state.swap(EMPTY, Acquire);
198-
unlock(self.lock.get());
107+
self.lock().unlock();
199108

200109
assert_eq!(old, NOTIFIED, "park state changed unexpectedly");
201110
return;
202111
} // should consume this notification, so prohibit spurious wakeups in next park.
203112
Err(_) => {
204-
unlock(self.lock.get());
113+
self.lock().unlock();
205114
panic!("inconsistent park_timeout state")
206115
}
207116
}
@@ -210,13 +119,13 @@ impl Parker {
210119
// from a notification we just want to unconditionally set the state back to
211120
// empty, either consuming a notification or un-flagging ourselves as
212121
// parked.
213-
wait_timeout(self.cvar.get(), self.lock.get(), dur);
122+
self.cvar().wait_timeout(self.lock(), dur);
214123

215124
match self.state.swap(EMPTY, Acquire) {
216-
NOTIFIED => unlock(self.lock.get()), // got a notification, hurray!
217-
PARKED => unlock(self.lock.get()), // no notification, alas
125+
NOTIFIED => self.lock().unlock(), // got a notification, hurray!
126+
PARKED => self.lock().unlock(), // no notification, alas
218127
n => {
219-
unlock(self.lock.get());
128+
self.lock().unlock();
220129
panic!("inconsistent park_timeout state: {n}")
221130
}
222131
}
@@ -248,21 +157,9 @@ impl Parker {
248157
// parked thread wakes it doesn't get woken only to have to wait for us
249158
// to release `lock`.
250159
unsafe {
251-
lock(self.lock.get());
252-
unlock(self.lock.get());
253-
notify_one(self.cvar.get());
160+
self.lock().lock();
161+
self.lock().unlock();
162+
self.cvar().notify_one();
254163
}
255164
}
256165
}
257-
258-
impl Drop for Parker {
259-
fn drop(&mut self) {
260-
unsafe {
261-
libc::pthread_cond_destroy(self.cvar.get_mut());
262-
libc::pthread_mutex_destroy(self.lock.get_mut());
263-
}
264-
}
265-
}
266-
267-
unsafe impl Sync for Parker {}
268-
unsafe impl Send for Parker {}

0 commit comments

Comments
 (0)
Please sign in to comment.