linux - 为什么 999µs 太短而 1000µs 恰到好处?

标签 linux rust rust-obsolete

当我运行以下代码时,我得到了一些输出:

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));
}

但是如果我将 DELAY 设置为 999,我什么也得不到。我认为 999 和 1000 足够接近,不会造成这样的差异,这意味着这里一定有其他事情发生。我也尝试过使用 Duration::nanoseconds(999_999 和 1_000_000),我看到了相同的行为。

我的平台是 Linux,我几乎总是可以重现此行为:使用 999 导致 一些输出 的运行次数不到 1%。


作为旁注,我知道这种方法 is wrong .

最佳答案

sleep 函数以 1 毫秒为增量休眠,如果毫秒数小于 1,则根本不休眠。这是相关的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);
}

在您的代码中,999 微秒使它根本没有休眠,并且主线程在生成的线程可以打印其输出之前结束。在 1000 微秒(即 1 毫秒)后,主线程进入休眠状态,让衍生线程有机会运行。

关于linux - 为什么 999µs 太短而 1000µs 恰到好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27803491/

相关文章:

c - 使用 proc 文件系统将信息从 LKM 写入用户空间

python - 计划任务 : how to run a script that requires to open display?

linux - FileNotFoundError:[Errno 2]推送到heroku之后

rust - Rust 出现 "cannot extract an associated type from a higher-ranked trait bound in this context"错误

module - 是否有可能有一个模块,部分可以在 crate 外部访问,部分只能在 crate 内部访问?

rust - 如何在 Rust 中借用可变与不可变?

rust - 什么是已弃用的 std::raw::Repr 的现代模拟?

linux - Linux SVN 服务器的问题

rust - 如何让 Rust 编译器解析从 std 导入?

rust - 通过共享框 ptr 访问时如何使我的结构字段可变?