Skip to content

Assertion fails in doc example for std::thread::sleep() in 1.32.0 stable #57772

Open
@TheRealOrangus

Description

@TheRealOrangus

The description of std::thread::sleep() says:

Puts the current thread to sleep for at least the specified amount of time.
The thread may sleep longer than the duration specified due to scheduling specifics or platform-dependent functionality. It will never sleep less.

and it gives the example code:

use std::{thread, time};

let ten_millis = time::Duration::from_millis(10);
let now = time::Instant::now();

thread::sleep(ten_millis);

assert!(now.elapsed() >= ten_millis);

But this assertion often fails when I run this code.

If the description is correct and it shouldn't fail, it happens on Windows 7 32 bit, stable-i686-pc-windows-gnu- rustc 1.32.0 (9fda7c223 2019-01-16)

EDIT:

Though, the expected behaviour can be achieved with this wrapper function:

use std::time::{Duration, Instant};
use std::thread::sleep;

fn sleep_noless(wanted_sleep: Duration) {
    let now = Instant::now();
    let mut slept_total = now.elapsed();
    while slept_total < wanted_sleep {
        sleep(wanted_sleep - slept_total);
        slept_total = now.elapsed();
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-timeArea: TimeC-bugCategory: This is a bug.O-windowsOperating system: WindowsT-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions