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
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.
