Rust program to create a simple thread

Rust | Thread Example: Write a program to create a simple thread.
Submitted by Nidhi, on November 02, 2021

Problem Solution:

In this program, we will create a simple thread and execute the thread with the main 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.

// 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);
    //main thread
    println!("Program finished");


Thread iteration: 0
Thread iteration: 1
Thread iteration: 2
Thread iteration: 3
Thread iteration: 4
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.

Rust Threads Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.