Rust Rayon Hello World

MPI - std::thread - Rayon

Writing a simple Rust Rayon program that will say hello from each processor thread

Rust Rayon Hello World

Rayon is a lightweight crate for using parallelism in Rust.

Add rayon to your cargo.toml file

[dependencies]
rayon = "1.7.0"
	

main.rs

	
use rayon::prelude::*;

fn main() {
// rayon-hello program uses the rayon crate to say Hello World from
// each available thread

// Create our message in shared memory.
    let shared_message = "Hello World".to_string();

// Get the number of available threads for parallelism.
    let num_threads = rayon::current_num_threads();

// Use Rayon's parallel iterator to concurrently execute the code on each thread.
    (0..num_threads).into_par_iter().for_each(|i| {
        
// Each thread prints message.
        println!("{} from thread {}", shared_message, i);
    });

	println!("All threads have completed!");
//end of fn main()
}
	

runtime output

	
me@pi:~/rust/rayon-hello$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/rayon-hello`
Hello World from thread 0
Hello World from thread 1
Hello World from thread 2
Hello World from thread 3
All threads have completed!
me@pi:~/rust/rayon-hello$
	

Mission Accomplished

And there we have it, because the rank is numbered from 0 the highest rank will be one less than the size.

Compared to the MPI and std::thread versions of our Hello World programs, the code is alot more compact. This is because Rayon works at a higher level so the programmer has less explicit coding to do.