linux-sysprog · beginner · ~10 min

Predict the result of a mutex-protected counter

The deterministic-total contract of mutex-protected mutations.

Challenge

Two threads each call bump() n_per_thread times. Each bump() increments a shared counter exactly once, protected by a mutex.

Implement long expected_counter(int n_per_thread) returning the FINAL expected value of the counter after both threads finish.

(This exercise tests that you understand the contract — mutex-protected increments produce a deterministic total. The actual pthread plumbing is in the lesson.)

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.

Output format

2 * n_per_thread.

Constraints

Pure arithmetic.

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.