linux-sysprog · intermediate · ~15 min
Recognise the symptom of an unsynchronised increment race.
When two threads do unsynchronised read-modify-write on a shared counter, increments can overwrite each other, so the final value falls short of the correct total. Detect that symptom.
Implement int lost_update(int initial, int incs_a, int incs_b, int observed) that returns 1 if observed is less than the correct total, else 0.
initial: starting counter value.incs_a, incs_b: increments each thread performed.observed: the final counter value seen.1 if observed < initial + incs_a + incs_b (updates were lost); else 0.
lost_update(0, 100, 100, 150) -> 1
lost_update(0, 100, 100, 200) -> 0
lost_update(5, 10, 10, 20) -> 1
observed equal to the correct total: return 0.initial: start value; incs_a/incs_b: per-thread increments; observed: final value.
1 if observed < initial + incs_a + incs_b, else 0.
Observed equal to the correct total is not a lost update.
int lost_update(int initial, int incs_a, int incs_b, int observed) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.