w3resource

Rust Parallel Sum Calculation with Threads

Rust Threads and Synchronization: Exercise-8 with Solution

Write a Rust program to calculate the sum of elements in a large array using multiple threads.

Sample Solution:

Rust Code:

// Import the 'thread' module from the standard library
use std::thread;

// Define a constant for the number of threads
const NUM_THREADS: usize = 4;

// Entry point of the program
fn main() {
    // Define the input data as a vector of integers
    let data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    
    // Calculate the chunk size for each thread
    let chunk_size = data.len() / NUM_THREADS;

    // Initialize a vector to store thread handles
    let mut handles = vec![];

    // Iterate over each thread
    for i in 0..NUM_THREADS {
        // Calculate the start index of the chunk
        let chunk_start = i * chunk_size;
        // Calculate the end index of the chunk
        let chunk_end = if i == NUM_THREADS - 1 {
            data.len() // If it's the last thread, use the full length of the data
        } else {
            (i + 1) * chunk_size // Otherwise, calculate based on chunk size
        };

        // Extract a chunk of data for each thread
        let chunk = data[chunk_start..chunk_end].to_vec();

        // Spawn a new thread with a closure to calculate the sum of the chunk
        let handle = thread::spawn(move || {
            let sum: i32 = chunk.iter().sum(); // Calculate the sum of elements in the chunk
            sum // Return the sum
        });

        // Store the handle of the spawned thread
        handles.push(handle);
    }

    // Initialize a variable to store the total sum of elements
    let mut total_sum = 0;

    // Iterate over each thread handle
    for handle in handles {
        // Wait for the thread to finish and get its result
        let sum = handle.join().unwrap();
        // Add the chunk sum to the total sum
        total_sum += sum;
    }

    // Print the total sum of elements
    println!("Total sum of elements: {}", total_sum);
}

Output:

Total sum of elements: 55

Explanation:

In the exercise above,

  • Define a constant 'NUM_THREADS' to specify the number of threads to be used for parallel processing.
  • In the main function,
    • An input data vector 'data' containing integers is defined.
    • The size of each chunk is calculated based on the length of the data vector and the number of threads.
    • A vector 'handles' is initialized to store thread handles.
  • A loop iterates over each thread:
    • Calculates the start and end indices of the chunk for each thread.
    • Extracts a chunk of data from the input vector for processing by the thread.
    • Spawns a new thread using thread::spawn, passing it a closure that calculates the sum of elements in the chunk.
    • The thread handle is stored in the 'handles' vector.
  • After all threads have been spawned, another loop iterates over each thread handle:
    • Wait for each thread to finish its execution using 'join'.
    • Retrieves the result (sum of chunk elements) from each thread.
    • Accumulates chunk sums to compute the total sum of elements.
  • Finally, the total sum of elements is printed to the console.

Rust Code Editor:

Previous: Rust Parallel Merge Sort Algorithm with Threads.
Next: Rust Deadlock Prevention with Mutexes.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.