How to do it...

The following steps will walk you through this implementation:

  1. Create a file named sample_thread_expt.rs and open it in your text editor.
  2. Write the code header with the relevant information:
        //-- #########################
//-- Task: Spawning 10 threads in rust
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 19 March 17
//-- #########################
  1. Call the standard thread library using the use keyword and create a static variable called NO_THREADS using the 32-bit integer value 10:
        // Using the standard thread crate
use std::thread;

// static value NO_THREADS
static NO_THREADS: i32 = 10;
  1. Define the main function and declare an empty thread_holder vector. Then create the corresponding loops for pushing the threads spawned to the vector with the iterator value i and return them later:
        // Main thread starts here
fn main() {
// Make a mutable vector named thread_holder to hold the
threads spawned
let mut thread_holder = vec![];

for i in 0..NO_THREADS {
// Spin up another thread
thread_holder.push(thread::spawn(move || {
println!("Thread number is {}", i);
i
}));
}

println!("***************************");

for thread_elements in thread_holder {
// Wait for the thread to finish. Returns a result.
println!("Thread returned {:?}",
thread_elements.join().unwrap());
}
}

We will get the following screenshot as output upon successful execution of the code:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.78.237