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

404 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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.

2
On

The most probable thing is you have your kernel configured to have a TICK of 1000Hz (once clock interrupt per millisecond) Perhaps you can improve it recompiling on a finer grained clock or a tickless kernel and recompiling your kernel to allow finer clock resolution. The 1000Hz clock tick is nowadays standard in Linux kernels running on pc (and most of ARMs and embedded Linux).

This is not a newbie issue, so perhaps you'll have to ask for local help to reconfigure and recompile your kernel to cope with more time resolution.