linux-sysprog · beginner · ~10 min
The deterministic-total contract of mutex-protected mutations.
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.)
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.
2 * n_per_thread.
Pure arithmetic.
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.