Adds thread::sleep_until, tracking issue TODO
APC (API change proposal): https://github.com/rust-lang/libs-team/issues/237
This commit is contained in:
parent
a482149598
commit
4854fc9646
1 changed files with 66 additions and 0 deletions
|
@ -872,6 +872,72 @@ pub fn sleep(dur: Duration) {
|
|||
imp::Thread::sleep(dur)
|
||||
}
|
||||
|
||||
/// Puts the current thread to sleep until the specified deadline has passed.
|
||||
///
|
||||
/// The thread may still be asleep after the deadline specified due to
|
||||
/// scheduling specifics or platform-dependent functionality. It will never
|
||||
/// wake before.
|
||||
///
|
||||
/// This function is blocking, and should not be used in `async` functions.
|
||||
///
|
||||
/// # Platform-specific behavior
|
||||
///
|
||||
/// This function uses ['sleep'] internally, see its platform-specific behaviour.
|
||||
///
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// A simple game loop that limits the game to 60 frames per second.
|
||||
///
|
||||
/// '''no_run
|
||||
/// # use std::time::{Duration, Instant};
|
||||
/// # use std::thread;
|
||||
/// #
|
||||
/// let max_fps = 60.0;
|
||||
/// let frame_time = Duration::from_secs_f32(1.0/max_fps);
|
||||
/// let mut next_frame = Instant::now();
|
||||
/// loop {
|
||||
/// thread::sleep_until(next_frame);
|
||||
/// next_frame += frame_time;
|
||||
/// update();
|
||||
/// render();
|
||||
/// }
|
||||
/// '''
|
||||
///
|
||||
/// 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
|
||||
///
|
||||
/// ```no_run
|
||||
/// # use std::time::{Duration, Instant};
|
||||
/// # use std::thread;
|
||||
/// #
|
||||
/// # const MAX_DURATION: Duration = Duration::from_secs(10);
|
||||
/// #
|
||||
/// let deadline = Instant::now() + MAX_DURATION;
|
||||
/// let delay = Duration::from_millis(250);
|
||||
/// let mut next_attempt = Instant::now();
|
||||
/// loop {
|
||||
/// if Instant::now() > deadline {
|
||||
/// break Err(()),
|
||||
/// }
|
||||
/// if let Ready(data) = slow_web_api_call() {
|
||||
/// break Ok(data),
|
||||
/// }
|
||||
///
|
||||
/// next_attempt = deadline.min(next_attempt + delay);
|
||||
/// thread::sleep_until(next_attempt);
|
||||
/// }
|
||||
/// ```
|
||||
#[unstable(feature = "thread_sleep_until", issue = "todo")]
|
||||
pub fn sleep_untill(deadline: Instant) {
|
||||
let now = Instant::now();
|
||||
|
||||
if let Some(delay) = deadline.checked_duration_since(now) {
|
||||
thread::sleep(delay);
|
||||
}
|
||||
}
|
||||
|
||||
/// Used to ensure that `park` and `park_timeout` do not unwind, as that can
|
||||
/// cause undefined behaviour if not handled correctly (see #102398 for context).
|
||||
struct PanicGuard;
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue