Q:

Rust program to demonstrate the join() function in threads

belongs to collection: Rust Threads Programs

0

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.

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 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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Rust program to access the main thread variable in... >>
<< Rust program to pause a thread for two seconds...