Q:

Rust program to create a thread pool

belongs to collection: Rust Threads Programs

0

In this program, we will create a pool of threads and execute them simultaneously.

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 thread pool is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to create a thread pool

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

fn main() {
    thread::spawn(|| {
        for cnt in 0..5 {
            println!("Thread1: {}", cnt);
            thread::sleep(Duration::from_millis(500));
        }
    });

     thread::spawn(|| {
        for cnt in 0..5 {
            println!("Thread2: {}", cnt);
            thread::sleep(Duration::from_millis(500));
        }
    });	

    //main thread	
     for cnt in 0..5 {
            println!("Main Thread: {}", cnt);
            thread::sleep(Duration::from_millis(500));
     }
    
    println!("Program finished");
}

Output:

$ rustc main.rs
$ ./main
Main Thread: 0
Thread1: 0
Thread2: 0
Thread2: 1
Main Thread: 1
Thread1: 1
Thread2: 2
Main Thread: 2
Thread1: 2
Thread2: 3
Main Thread: 3
Thread1: 3
Thread2: 4
Main Thread: 4
Thread1: 4
Program finished

Explanation:

Here, we created a pool of threads using thread:spawn() function and executed them concurrently and printed messages.

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

total answers (1)

Rust program to pause a thread for two seconds... >>
<< Rust program to create a simple thread...