linux-sysprog · beginner · ~10 min

Predict the result of a mutex-protected counter

The deterministic-total contract of mutex-protected mutations.

Challenge

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.

Task

Implement long expected_counter(int n_per_thread) that returns the counter's final value.

Input

  • n_per_thread: how many times each of the two threads increments the shared counter.

Output

Returns the deterministic final total: 2 * n_per_thread (two threads, each adding n_per_thread).

Example

expected_counter(100)      ->   200
expected_counter(1)        ->   2
expected_counter(0)        ->   0
expected_counter(1000000)  ->   2000000

Edge cases

  • n_per_thread == 0 returns 0.
  • Use a long so large values don't overflow.

Why this matters

The single most-asked concurrency question. Two threads bumping a counter — protected, the result is deterministic; unprotected, it's a data race.

Input format

n_per_thread: the number of increments performed by each of the two threads.

Output format

The deterministic final counter value, 2 * n_per_thread, as a long.

Constraints

Two threads, so the total is 2 * n_per_thread. Compute in long to avoid overflow.

Starter code

long expected_counter(int n_per_thread) { /* TODO */ (void)n_per_thread; return 0; }

Common mistakes

Returning n_per_thread (forgetting one of the threads).

Edge cases to handle

n_per_thread = 0; very large value.

Complexity

O(1).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.