Rust Program: Calculate Factorial with Threads
Write a program to calculate the factorial of a number using multiple threads.
Sample Solution:
Rust Code:
use std::thread;
use std::sync::{Arc, Mutex};
fn main() {
let n = 7; // Number to calculate factorial
// Create a shared variable to store the result
let result = Arc::new(Mutex::new(1));
// Create a vector to hold the thread handles
let mut handles = vec![];
// Spawn threads to calculate factorial
for i in 1..=n {
let result = Arc::clone(&result);
let handle = thread::spawn(move || {
let mut result = result.lock().unwrap();
*result *= i;
});
handles.push(handle);
}
// Wait for all threads to finish
for handle in handles {
handle.join().unwrap();
}
// Print the factorial result
let result = result.lock().unwrap();
println!("Factorial of {} is: {}", n, *result);
}
Output:
Factorial of 7 is: 5040
Explanation:
In the exercise above,
- Imports:
- std::thread: Provides the threading functionality.
- std::sync::{Arc, Mutex}: Provides synchronization primitives for safe concurrent access.
- Main Function:
- Sets the value of 'n' to the number for which we want to calculate the factorial.
- Shared Variable:
- Create a shared variable 'result' using an 'Arc' (atomic reference counting) wrapped around a 'Mutex' (mutual exclusion), initialized with the value 1. This variable stores the final factorial result.
- Thread Spawning:
- Iterates from '1' to 'n' and spawns a thread for each iteration.
- Each thread receives a clone of the shared 'result' variable.
- Inside each thread, it locks the 'result' mutex, multiplies its current value by the thread's corresponding number, and then releases the lock.
- Waiting for Threads to Finish:
- After spawning all threads, the main thread iterates through the vector of thread handles and waits for each thread to finish by calling "join()".
- Printing the Result:
- After all threads have finished, the main thread locks the 'result' mutex to access the final factorial value and prints it.
Rust Code Editor:
Previous: Rust Program: Implement Producer-Consumer Pattern with Threads & Channels.
Next: Rust Program: Matrix Multiplication with Parallel Threads.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics