Home »
Rust »
Rust Programs
Rust program to create a thread pool
Rust | Thread Example: Write a program to create a thread pool.
Submitted by Nidhi, on November 02, 2021
Problem Solution:
In this program, we will create a pool of threads and execute them simultaneously.
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.
Rust Threads Programs »