Skip to content

Commit f1f39d1

Browse files
committed
sleep_until: Fix error handling + improve maintainablity
- In contradiction to nanosleep clock_nanosleep returns the error directly and does not require a call to `os::errno()`. - The last argument to clock_nanosleep can be NULL removing the need for mutating the timespec. - Missed an `allow(unused)` that could be made conditional.
1 parent 1626d55 commit f1f39d1

File tree

2 files changed

+23
-17
lines changed

2 files changed

+23
-17
lines changed

library/std/src/sys/pal/unix/thread.rs

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -310,7 +310,7 @@ impl Thread {
310310
target_os = "vxworks",
311311
))]
312312
pub fn sleep_until(deadline: Instant) {
313-
let Some(mut ts) = deadline.into_inner().into_timespec().to_timespec() else {
313+
let Some(ts) = deadline.into_inner().into_timespec().to_timespec() else {
314314
// The deadline is further in the future then can be passed to
315315
// clock_nanosleep. We have to use Self::sleep intead. This might
316316
// happen on 32 bit platforms, especially closer to 2038.
@@ -321,23 +321,26 @@ impl Thread {
321321
return;
322322
};
323323

324-
let ts_ptr = &mut ts as *mut _;
325-
326-
// If we're awoken with a signal and the return value is -1
327-
// clock_nanosleep needs to be called again.
328324
unsafe {
329-
while libc::clock_nanosleep(
330-
super::time::Instant::CLOCK_ID,
331-
libc::TIMER_ABSTIME,
332-
ts_ptr,
333-
ts_ptr,
334-
) == -1
335-
{
336-
assert_eq!(
337-
os::errno(),
338-
libc::EINTR,
339-
"clock nanosleep should only return an error if interrupted"
325+
// When we get interrupted (res = EINTR) call clock_nanosleep again
326+
loop {
327+
let res = libc::clock_nanosleep(
328+
super::time::Instant::CLOCK_ID,
329+
libc::TIMER_ABSTIME,
330+
&ts,
331+
core::ptr::null_mut(), // not required with TIMER_ABSTIME
340332
);
333+
334+
if res == 0 {
335+
break;
336+
} else {
337+
assert_eq!(
338+
res,
339+
libc::EINTR,
340+
"timespec is in range,
341+
clockid is valid and kernel should support it"
342+
);
343+
}
341344
}
342345
}
343346
}

library/std/src/sys/pal/unix/time.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,10 @@ impl Instant {
292292
Some(Instant { t: self.t.checked_sub_duration(other)? })
293293
}
294294

295-
#[allow(unused, reason = "needed by the `sleep_until` on some unix platforms")]
295+
#[cfg_attr(
296+
not(target_os = "linux"),
297+
allow(unused, reason = "needed by the `sleep_until` on some unix platforms")
298+
)]
296299
pub(crate) fn into_timespec(self) -> Timespec {
297300
self.t
298301
}

0 commit comments

Comments
 (0)