ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.