Rust std::thread Hello World

MPI - std::thread - Rayon

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

Rust std::thread Hello World

Rust has a standard threading model, std::thread, which takes advantage of OS native threading.

In this program we use thread::available_parallelisum() to work out how many threads the local computer has for us to work with.

Next we create a message in memory to share between the threads and create an atomic referace to the shared message for each thread.

Finally we get yo print the shared message, together with the thread number that printed it.

And lastly we wait for all the threads to complete before the end of the program

	
use std::thread;
use std::sync::Arc;

fn main() {
// hellothread program creates a string in shared memory and then
// each thread prints the string together with its thread number.

// find the number of threads the cpu can use
    let num_threads = match thread::available_parallelism() {
        Ok(count) => count.get(),
        Err(e) => {
            eprintln!("Failed to get available parallelism: {}. Defaulting to 4 threads.", e);
            4
        }
    };
    	
// create our message in shared memory
	let shared_message = Arc::new("Hello World!".to_string());
	
// Create and join threads
	let handles: Vec<_> = (0..num_threads).map(|i| {

// Create atomic reference to our shared message
		let thread_message = Arc::clone(&shared_message);
		
// Spawn the threads and print the message
		thread::spawn(move || {
            println!("{} from thread {}", thread_message, i);
        })
    }).collect();
    
// Wait for all threads to complete before end of main
    for handle in handles {
        handle.join().unwrap();
    }

// end of fn main()
}	

runtime output

	
me@pi:~/rust/hellothread$ cargo run
   Compiling hellothread v0.1.0 (~/rust/hellothread)
    Finished dev [unoptimized + debuginfo] target(s) in 0.39s
     Running `target/debug/hellothread`
Hello World! from thread 0
Hello World! from thread 2
Hello World! from thread 3
Hello World! from thread 1
me@pi:~/rust/hellothread$
	

Mission Accomplished

And there we have it, because the threads are numbered from 0 the highest thread number will be one less than the total number of available threads.