Code Logo

Thread-Safe Counter with Arc Mutex

Published at25 Jul 2026
Rust Functions Hard 0 views
Like0

Write a Rust function that spawns multiple threads, each incrementing a shared counter a given number of times, using Arc> for safe concurrent access. The function takes the number of threads and the number of increments per thread, and returns the final counter value.

Arc> is the standard way to share mutable state across threads in Rust. Arc (Atomic Reference Counting) enables multiple ownership across threads, while Mutex ensures mutual exclusion — only one thread can access the inner value at a time. This combination guarantees thread safety at compile time without a garbage collector.

Rust's type system enforces thread safety through the Send and Sync traits. Arc is Send and Sync when T is Send and Sync. Mutex is Send and Sync when T is Send. The compiler checks these traits at compile time, preventing data races and undefined behavior that plague concurrent programs in other languages.

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

Example 1
Input
3,2
Output
6
Explanation

3 threads × 2 increments = 6

Example 2
Input
5,3
Output
15
Explanation

5 threads × 3 increments = 15

Example 3
Input
4,5
Output
20
Explanation

4 threads × 5 increments = 20

Example 4
Input
1,1
Output
1
Explanation

1 thread × 1 increment = 1

Example 5
Input
2,0
Output
0
Explanation

2 threads × 0 increments = 0

Algorithm Flow

Recommendation Algorithm Flow for Thread-Safe Counter with Arc Mutex
Recommendation Algorithm Flow for Thread-Safe Counter with Arc Mutex

Solution Approach

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
}

Best Answers

rust - Approach 1
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
}