Rust program to pause a thread for two seconds

Rust | Thread Example: Write a program to pause a thread for two seconds.
Submitted by Nidhi, on November 02, 2021

Problem Solution:

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.

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.

Rust Threads Programs »



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.