Q:

Rust program to pause a thread for two seconds

belongs to collection: Rust Threads Programs

0

In this program, we will create a thread inside the body of the main thread. Here, we will pause the main thread for 2 seconds using the thread:sleep() method.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to pause a thread for 2 seconds is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to pause a 
// thread for two seconds

use std::thread;
use std::time::Duration;

fn main() {
    thread::spawn(|| {
        for cnt in 0..5 
        {
            println!("Thread: {}", cnt);
        }
    });
    
    println!("Sleep Main thread for 2 seconds");
    thread::sleep(Duration::from_millis(2000));
    println!("Program finished");
}

Output:

$ rustc main.rs
$ ./main
Sleep Main thread for 2 seconds
Thread: 0
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Program finished

Explanation:

Here, we created a thread using thread:spawn() function. The created thread contains a for loop and printed some messages on the console screen. In the main() function, we used the thread::sleep() method to pause the main thread for 2 seconds.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Rust program to demonstrate the join() function in... >>
<< Rust program to create a thread pool...