Skip to content

Specialize sleep_until implementation for unix (except mac) #141829

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion library/std/src/sys/pal/hermit/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use super::hermit_abi;
use crate::ffi::CStr;
use crate::mem::ManuallyDrop;
use crate::num::NonZero;
use crate::time::Duration;
use crate::time::{Duration, Instant};
use crate::{io, ptr};

pub type Tid = hermit_abi::Tid;
Expand Down Expand Up @@ -86,6 +86,14 @@ impl Thread {
}
}

pub fn sleep_until(deadline: Instant) {
let now = Instant::now();

if let Some(delay) = deadline.checked_duration_since(now) {
Self::sleep(delay);
}
}

pub fn join(self) {
unsafe {
let _ = hermit_abi::join(self.tid);
Expand Down
10 changes: 9 additions & 1 deletion library/std/src/sys/pal/itron/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::mem::ManuallyDrop;
use crate::num::NonZero;
use crate::ptr::NonNull;
use crate::sync::atomic::{Atomic, AtomicUsize, Ordering};
use crate::time::Duration;
use crate::time::{Duration, Instant};
use crate::{hint, io};

pub struct Thread {
Expand Down Expand Up @@ -205,6 +205,14 @@ impl Thread {
}
}

pub fn sleep_until(deadline: Instant) {
let now = Instant::now();

if let Some(delay) = deadline.checked_duration_since(now) {
Self::sleep(delay);
}
}

pub fn join(self) {
// Safety: `ThreadInner` is alive at this point
let inner = unsafe { self.p_inner.as_ref() };
Expand Down
10 changes: 9 additions & 1 deletion library/std/src/sys/pal/sgx/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use super::unsupported;
use crate::ffi::CStr;
use crate::io;
use crate::num::NonZero;
use crate::time::Duration;
use crate::time::{Duration, Instant};

pub struct Thread(task_queue::JoinHandle);

Expand Down Expand Up @@ -132,6 +132,14 @@ impl Thread {
usercalls::wait_timeout(0, dur, || true);
}

pub fn sleep_until(deadline: Instant) {
let now = Instant::now();

if let Some(delay) = deadline.checked_duration_since(now) {
Self::sleep(delay);
}
}

pub fn join(self) {
self.0.wait();
}
Expand Down
10 changes: 9 additions & 1 deletion library/std/src/sys/pal/teeos/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::ffi::CStr;
use crate::mem::{self, ManuallyDrop};
use crate::num::NonZero;
use crate::sys::os;
use crate::time::Duration;
use crate::time::{Duration, Instant};
use crate::{cmp, io, ptr};

pub const DEFAULT_MIN_STACK_SIZE: usize = 8 * 1024;
Expand Down Expand Up @@ -109,6 +109,14 @@ impl Thread {
}
}

pub fn sleep_until(deadline: Instant) {
let now = Instant::now();

if let Some(delay) = deadline.checked_duration_since(now) {
Self::sleep(delay);
}
}

/// must join, because no pthread_detach supported
pub fn join(self) {
let id = self.into_id();
Expand Down
10 changes: 9 additions & 1 deletion library/std/src/sys/pal/uefi/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::ffi::CStr;
use crate::io;
use crate::num::NonZero;
use crate::ptr::NonNull;
use crate::time::Duration;
use crate::time::{Duration, Instant};

pub struct Thread(!);

Expand Down Expand Up @@ -39,6 +39,14 @@ impl Thread {
}
}

pub fn sleep_until(deadline: Instant) {
let now = Instant::now();

if let Some(delay) = deadline.checked_duration_since(now) {
Self::sleep(delay);
}
}

pub fn join(self) {
self.0
}
Expand Down
64 changes: 63 additions & 1 deletion library/std/src/sys/pal/unix/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::sys::weak::dlsym;
#[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto",))]
use crate::sys::weak::weak;
use crate::sys::{os, stack_overflow};
use crate::time::Duration;
use crate::time::{Duration, Instant};
use crate::{cmp, io, ptr};
#[cfg(not(any(
target_os = "l4re",
Expand Down Expand Up @@ -296,6 +296,68 @@ impl Thread {
}
}

// Any unix that has clock_nanosleep
#[cfg(any(
target_os = "freebsd",
target_os = "netbsd",
target_os = "linux",
target_os = "android",
target_os = "solaris",
target_os = "illumos",
target_os = "dragonfly",
target_os = "hurd",
target_os = "fuchsia",
target_os = "vxworks",
))]
pub fn sleep_until(deadline: Instant) {
let Some(mut ts) = deadline.into_inner().into_timespec().to_timespec() else {
// The deadline is further in the future then can be passed to
// clock_nanosleep. We have to use Self::sleep intead. This might
// happen on 32 bit platforms, especially closer to 2038.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't necessarily need to deal with this now, but 32-bit glibc also has __clock_nanosleep_time64 for future-proofing, which could use like this __clock_gettime64 code:

// Try to use 64-bit time in preparation for Y2038.
#[cfg(all(
target_os = "linux",
target_env = "gnu",
target_pointer_width = "32",
not(target_arch = "riscv32")
))]
{
use crate::sys::weak::weak;
// __clock_gettime64 was added to 32-bit arches in glibc 2.34,
// and it handles both vDSO calls and ENOSYS fallbacks itself.
weak!(
fn __clock_gettime64(
clockid: libc::clockid_t,
tp: *mut __timespec64,
) -> libc::c_int;
);
if let Some(clock_gettime64) = __clock_gettime64.get() {
let mut t = MaybeUninit::uninit();
cvt(unsafe { clock_gettime64(clock, t.as_mut_ptr()) }).unwrap();
let t = unsafe { t.assume_init() };
return Timespec::new(t.tv_sec as i64, t.tv_nsec as i64).unwrap();
}
}

let now = Instant::now();
if let Some(delay) = deadline.checked_duration_since(now) {
Self::sleep(delay);
}
return;
};

let ts_ptr = &mut ts as *mut _;

// If we're awoken with a signal and the return value is -1
// clock_nanosleep needs to be called again.
unsafe {
while libc::clock_nanosleep(libc::CLOCK_MONOTONIC, libc::TIMER_ABSTIME, ts_ptr, ts_ptr)
== -1
{
assert_eq!(
os::errno(),
libc::EINTR,
"clock nanosleep should only return an error if interrupted"
);
}
}
}

// Any unix that does not have clock_nanosleep
#[cfg(not(any(
target_os = "freebsd",
target_os = "netbsd",
target_os = "linux",
target_os = "android",
target_os = "solaris",
target_os = "illumos",
target_os = "dragonfly",
target_os = "hurd",
target_os = "fuchsia",
target_os = "vxworks",
)))]
pub fn sleep_until(deadline: Instant) {
let now = Instant::now();
if let Some(delay) = deadline.checked_duration_since(now) {
Self::sleep(delay);
}
}

pub fn join(self) {
let id = self.into_id();
let ret = unsafe { libc::pthread_join(id, ptr::null_mut()) };
Expand Down
5 changes: 5 additions & 0 deletions library/std/src/sys/pal/unix/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,11 @@ impl Instant {
pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
Some(Instant { t: self.t.checked_sub_duration(other)? })
}

#[allow(unused, reason = "needed by the `sleep_until` on some unix platforms")]
pub(crate) fn into_timespec(self) -> Timespec {
self.t
}
}

impl fmt::Debug for Instant {
Expand Down
4 changes: 4 additions & 0 deletions library/std/src/sys/pal/unsupported/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ impl Thread {
panic!("can't sleep");
}

pub fn sleep_until(_deadline: Instant) {
panic!("can't sleep");
}

pub fn join(self) {
self.0
}
Expand Down
10 changes: 9 additions & 1 deletion library/std/src/sys/pal/wasi/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use crate::ffi::CStr;
use crate::num::NonZero;
use crate::time::Duration;
use crate::time::{Duration, Instant};
use crate::{io, mem};

cfg_if::cfg_if! {
Expand Down Expand Up @@ -171,6 +171,14 @@ impl Thread {
}
}

pub fn sleep_until(deadline: Instant) {
let now = Instant::now();

if let Some(delay) = deadline.checked_duration_since(now) {
Self::sleep(delay);
}
}

pub fn join(self) {
cfg_if::cfg_if! {
if #[cfg(target_feature = "atomics")] {
Expand Down
10 changes: 9 additions & 1 deletion library/std/src/sys/pal/wasm/atomics/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::ffi::CStr;
use crate::io;
use crate::num::NonZero;
use crate::sys::unsupported;
use crate::time::Duration;
use crate::time::{Duration, Instant};

pub struct Thread(!);

Expand Down Expand Up @@ -41,6 +41,14 @@ impl Thread {
}
}

pub fn sleep_until(deadline: Instant) {
let now = Instant::now();

if let Some(delay) = deadline.checked_duration_since(now) {
Self::sleep(delay);
}
}

pub fn join(self) {}
}

Expand Down
10 changes: 9 additions & 1 deletion library/std/src/sys/pal/windows/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::os::windows::io::{AsRawHandle, HandleOrNull};
use crate::sys::handle::Handle;
use crate::sys::{c, stack_overflow};
use crate::sys_common::FromInner;
use crate::time::Duration;
use crate::time::{Duration, Instant};
use crate::{io, ptr};

pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
Expand Down Expand Up @@ -106,6 +106,14 @@ impl Thread {
}
}

pub fn sleep_until(deadline: Instant) {
let now = Instant::now();

if let Some(delay) = deadline.checked_duration_since(now) {
Self::sleep(delay);
}
}

pub fn handle(&self) -> &Handle {
&self.handle
}
Expand Down
10 changes: 9 additions & 1 deletion library/std/src/sys/pal/xous/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::os::xous::ffi::{
map_memory, update_memory_flags,
};
use crate::os::xous::services::{TicktimerScalar, ticktimer_server};
use crate::time::Duration;
use crate::time::{Duration, Instant};

pub struct Thread {
tid: ThreadId,
Expand Down Expand Up @@ -128,6 +128,14 @@ impl Thread {
}
}

pub fn sleep_until(deadline: Instant) {
let now = Instant::now();

if let Some(delay) = deadline.checked_duration_since(now) {
Self::sleep(delay);
}
}

pub fn join(self) {
join_thread(self.tid).unwrap();
}
Expand Down
39 changes: 30 additions & 9 deletions library/std/src/thread/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -897,8 +897,33 @@ pub fn sleep(dur: Duration) {
///
/// # Platform-specific behavior
///
/// This function uses [`sleep`] internally, see its platform-specific behavior.
///
/// In most cases this function will call an OS specific function. Where that
/// is not supported [`sleep`] is used. Those platforms are referred to as other
/// in the table below.
///
/// # Underlying System calls
///
/// The following system calls are [currently] being used:
///
/// | Platform | System call |
/// |-----------|----------------------------------------------------------------------|
/// | Linux | [clock_nanosleep] (Monotonic clock) |
/// | BSD except OpenBSD | [clock_nanosleep] (Monotonic Clock)] |
/// | Android | [clock_nanosleep] (Monotonic Clock)] |
/// | Solaris | [clock_nanosleep] (Monotonic Clock)] |
/// | Illumos | [clock_nanosleep] (Monotonic Clock)] |
/// | Dragonfly | [clock_nanosleep] (Monotonic Clock)] |
/// | Hurd | [clock_nanosleep] (Monotonic Clock)] |
/// | Fuchsia | [clock_nanosleep] (Monotonic Clock)] |
/// | Vxworks | [clock_nanosleep] (Monotonic Clock)] |
/// | Other | `sleep_until` uses [`sleep`] and does not issue a syscall itself |
///
/// [currently]: crate::io#platform-specific-behavior
/// [clock_nanosleep]: https://linux.die.net/man/3/clock_nanosleep
/// [subscription_clock]: https://github.com/WebAssembly/WASI/blob/main/legacy/preview1/docs.md#-subscription_clock-record
/// [mach_wait_until]: https://developer.apple.com/library/archive/technotes/tn2169/_index.html
///
/// **Disclaimer:** These system calls might change over time.
///
/// # Examples
///
Expand All @@ -923,9 +948,9 @@ pub fn sleep(dur: Duration) {
/// }
/// ```
///
/// A slow api we must not call too fast and which takes a few
/// A slow API we must not call too fast and which takes a few
/// tries before succeeding. By using `sleep_until` the time the
/// api call takes does not influence when we retry or when we give up
/// API call takes does not influence when we retry or when we give up
///
/// ```no_run
/// #![feature(thread_sleep_until)]
Expand Down Expand Up @@ -960,11 +985,7 @@ pub fn sleep(dur: Duration) {
/// ```
#[unstable(feature = "thread_sleep_until", issue = "113752")]
pub fn sleep_until(deadline: Instant) {
let now = Instant::now();

if let Some(delay) = deadline.checked_duration_since(now) {
sleep(delay);
}
imp::Thread::sleep_until(deadline)
}

/// Used to ensure that `park` and `park_timeout` do not unwind, as that can
Expand Down
6 changes: 6 additions & 0 deletions library/std/src/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,12 @@ impl Instant {
pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
self.0.checked_sub_duration(&duration).map(Instant)
}

// used by platform specific `sleep_until` implementations.
#[allow(unused, reason = "not every platform has a specific `sleep_until`")]
pub(crate) fn into_inner(self) -> time::Instant {
self.0
}
}

#[stable(feature = "time2", since = "1.8.0")]
Expand Down
Loading
Loading