【问题标题】:How can I put the current thread to sleep?如何让当前线程进入睡眠状态?
【发布时间】:2015-03-09 22:30:35
【问题描述】:

有太多过时的信息,真的很难找到如何睡觉。我想要类似于此 Java 代码的内容:

Thread.sleep(4000);

【问题讨论】:

    标签: rust sleep


    【解决方案1】:

    锈 1.4+

    Durationsleep 已返回且稳定!

    use std::{thread, time::Duration};
    
    fn main() {
        thread::sleep(Duration::from_millis(4000));
    }
    

    您也可以使用Duration::from_secs(4),在这种情况下可能更明显。

    由于语义版本控制的性质,如果您愿意,下面的 1.0 解决方案将继续有效。

    锈 1.0+

    在 1.0 中,持续时间没有及时稳定,所以镇上有一个新功能 - thread::sleep_ms

    use std::thread;
    
    fn main() {
        thread::sleep_ms(4000);
    }
    

    【讨论】:

      【解决方案2】:

      更新答案

      这是当前 Rust 版本的更新代码:

      use std::time::Duration;
      use std::thread::sleep;
      
      fn main() {
          sleep(Duration::from_millis(2));
      }
      

      Rust 播放网址:http://is.gd/U7Oyip

      1.0 之前的旧答案

      根据拉取请求https://github.com/rust-lang/rust/pull/23330,将替换旧std::old_io::timer::sleep 的功能是新std::thread::sleep

      GitHub 上的拉取请求说明:

      这个函数是 std::old_io::timer 的当前替代 很快就会被弃用。这个函数是不稳定的,有自己的 功能门,因为它还没有 RFC,也不存在 很长。

      代码示例:

      #![feature(std_misc, thread_sleep)]
      
      use std::time::Duration;
      use std::thread::sleep;
      
      fn main() {
          sleep(Duration::milliseconds(2));
      }
      

      这使用了sleepDuration,它们目前分别位于thread_sleepstd_misc 的特性门之后。

      【讨论】:

      • 错误:#[feature] 可能无法在稳定版本通道上使用。使用 #[feature] 解锁了许多精彩的 API,但是如果您从知名网站下载 Rust,您将无法使用 #[feature]。
      猜你喜欢
      • 1970-01-01
      • 2012-06-21
      • 2011-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多