Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is 999µs too short but 1000µs just right?

When I run the following code, I get some output:

use std::thread::Thread;

static DELAY: i64 = 1000;

fn main() {
    Thread::spawn(move || {
        println!("some output");
    });

    std::io::timer::sleep(std::time::duration::Duration::microseconds(DELAY));
}

But if I set DELAY to 999, I get nothing. I think that 999 and 1000 are close enough not to cause such a difference, meaning there must be something else going on here. I've tried also with Duration::nanoseconds (999_999 and 1_000_000), and I see the same behavior.

My platform is Linux and I can reproduce this behavior nearly all the time: using 999 results in some output in way less than 1% of runs.


As a sidenote, I am aware that this approach is wrong.

like image 668
tshepang Avatar asked Jan 06 '15 17:01

tshepang


1 Answers

The sleep function sleeps in increments of 1 millisecond, and if the number of milliseconds is less than 1 it does not sleep at all. Here is the relevant excerpt from the code:

pub fn sleep(&mut self, duration: Duration) {
    // Short-circuit the timer backend for 0 duration
    let ms = in_ms_u64(duration);
    if ms == 0 { return }
    self.inner.sleep(ms);
}

In your code, 999 microseconds made it not sleep at all, and the main thread ended before the spawned thread could print its output. With 1000 microseconds, i.e. 1 millisecond, the main thread slept, giving the spawned thread a chance to run.

like image 68
wingedsubmariner Avatar answered Sep 30 '22 09:09

wingedsubmariner