The source code to create a simple thread is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.
// Rust program to create a simple thread
use std::thread;
use std::time::Duration;
fn main() {
// create a thread
thread::spawn(|| {
for cnt in 0..5 {
println!("Thread iteration: {}", cnt);
}
});
thread::sleep(Duration::from_millis(500));
//main thread
println!("Program finished");
}
Here, we created a simple thread using thread:spawn() function. The thread contains a for loop it will execute 5 times and print the message. And, we used thread::sleep() function to stop main() thread for 500 milliseconds. If we did not use the thread:sleep() function in the main() thread then the spawn thread will not execute properly. Because the main thread is the parent thread.
Program/Source Code:
The source code to create a simple thread is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.
Output:
Explanation:
Here, we created a simple thread using thread:spawn() function. The thread contains a for loop it will execute 5 times and print the message. And, we used thread::sleep() function to stop main() thread for 500 milliseconds. If we did not use the thread:sleep() function in the main() thread then the spawn thread will not execute properly. Because the main thread is the parent thread.
need an explanation for this answer? contact us directly to get an explanation for this answer