Rust program to demonstrate the join() function in threads

Rust | Thread Example: Write a program to demonstrate the join() function in threads.
Submitted by Nidhi, on November 02, 2021

Problem Solution:

In this program, we will use the join() function to handle threads. Using the join() function, we can put the thread in the handle. Then join it with the handle of the main thread. This will let all the handles complete before the program exits.

Program/Source Code:

The source code to demonstrate the join() function in threads is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to demonstrate the join() 
// function in threads

use std::thread;
use std::time::Duration;

fn main() {
    let handle = thread::spawn(|| {
        for cnt in 0..5 
        {
            println!("Thread: {}", cnt);
            thread::sleep(Duration::from_millis(100));
        }
    });
    
    for cnt in 0..5 
    {
        println!("Main Thread: {}", cnt);
        thread::sleep(Duration::from_millis(100));
    }
    
    handle.join().unwrap();
    println!("Program finished");
}

Output:

$ rustc main.rs

$ ./main
Main Thread: 0
Thread: 0
Main Thread: 1
Thread: 1
Main Thread: 2
Thread: 2
Main Thread: 3
Thread: 3
Main Thread: 4
Thread: 4
Program finished

Explanation:

Here, we created a thread using the thread:spawn() function. The thread:spawn() function returns a handle. Then we joined the thread with the main thread using the join() function and executed the thread with the main() thread to print the message.

Rust Threads Programs »





Comments and Discussions!

Load comments ↻





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