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


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.