Q:

Rust program to create a simple thread

belongs to collection: Rust Threads Programs

0

In this program, we will create a simple thread and execute the thread with the main thread.

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 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");
}

Output:

Thread iteration: 0
Thread iteration: 1
Thread iteration: 2
Thread iteration: 3
Thread iteration: 4
Program finished

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

total answers (1)

Rust program to create a thread pool... >>