Thread-Safe Counter with Arc Mutex
Write a Rust function that spawns multiple threads, each incrementing a shared counter a given number of times, using Arc
Arc
Rust's type system enforces thread safety through the Send and Sync traits. Arc
Time complexity is O(n * m) where n is thread count and m is increments per thread. The mutex introduces some contention but for this simple workload it's minimal. Space complexity is O(n) for thread handles. The Arc pointer itself is O(1) regardless of how many clones exist.
Edge cases include zero increments (threads still spawn but immediately finish), single thread (no contention), large thread counts (system-dependent limit), and ensuring all threads complete before reading the final value via join handles.
Example Input & Output
3 threads × 2 increments = 6
5 threads × 3 increments = 15
4 threads × 5 increments = 20
1 thread × 1 increment = 1
2 threads × 0 increments = 0
Algorithm Flow
Solution Approach
Create a thread-safe counter in Rust using Arc and Mutex. Arc provides atomic reference-counted shared ownership across multiple threads. Mutex ensures mutual exclusion so only one thread can modify the counter at a time.
The lock() method returns a guard that automatically releases the Mutex when dropped. For read-heavy data, use RwLock which allows many readers or one writer.
Time O(1), Space O(n).
Best Answers
use std::sync::{Arc, Mutex};
use std::thread;
fn solution(num_threads: i32, increments: i32) -> i32 {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..num_threads {
let c = Arc::clone(&counter);
let handle = thread::spawn(move || {
for _ in 0..increments {
let mut val = c.lock().unwrap();
*val += 1;
}
});
handles.push(handle);
}
for h in handles { h.join().unwrap(); }
let final_val = *counter.lock().unwrap();
final_val
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
