linux-sysprog · beginner · ~10 min
The deterministic-total contract of mutex-protected mutations.
Predict the final value of a counter that two threads each increment a fixed number of times, when every increment is mutex-protected. Because the mutex makes the total deterministic, this reduces to a one-line calculation — no threads are actually run.
Implement long expected_counter(int n_per_thread) that returns the counter's final value.
n_per_thread: how many times each of the two threads increments the shared counter.Returns the deterministic final total: 2 * n_per_thread (two threads, each adding n_per_thread).
expected_counter(100) -> 200
expected_counter(1) -> 2
expected_counter(0) -> 0
expected_counter(1000000) -> 2000000
n_per_thread == 0 returns 0.long so large values don't overflow.The single most-asked concurrency question. Two threads bumping a counter — protected, the result is deterministic; unprotected, it's a data race.
n_per_thread: the number of increments performed by each of the two threads.
The deterministic final counter value, 2 * n_per_thread, as a long.
Two threads, so the total is 2 * n_per_thread. Compute in long to avoid overflow.
long expected_counter(int n_per_thread) { /* TODO */ (void)n_per_thread; return 0; }
Returning n_per_thread (forgetting one of the threads).
n_per_thread = 0; very large value.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.