📜  rust lang sleep - Rust (1)

📅  最后修改于: 2023-12-03 15:34:46.499000             🧑  作者: Mango

Rust Lang Sleep - Rust

Rust is a programming language that emphasizes on performance, safety, and concurrency. It is designed to provide a reliable and efficient way of writing systems-level software. One useful and commonly used feature in Rust is the sleep function.

Sleep Function in Rust

The std::thread::sleep function is used to make a thread sleep for a specified amount of time. This function takes one argument, which is a Duration struct representing the amount of time to sleep.

use std::time::Duration;

fn main() {
    println!("Going to sleep for 5 seconds...");
    std::thread::sleep(Duration::from_secs(5));
    println!("Woke up after 5 seconds!");
}

In this example, we have imported the Duration struct from the std::time module. We then called the sleep function and passed in a Duration of 5 seconds. The program will pause for 5 seconds and then print "Woke up after 5 seconds!" to the console.

Advanced Options

The sleep function can also be used with other units of time, such as milliseconds and nanoseconds. Here is an example that sleeps for 1 millisecond:

use std::time::Duration;

fn main() {
    println!("Going to sleep for 1 millisecond...");
    std::thread::sleep(Duration::from_millis(1));
    println!("Woke up after 1 millisecond!");
}

Additionally, the sleep function can be interrupted by another thread using the std::thread::Thread::interrupt method.

Conclusion

The std::thread::sleep function is a useful tool in Rust for handling concurrency and achieving better performance in your programs. With Rust's focus on safety and reliability, you can be sure that your threads will sleep exactly as long as intended.