linux-sysprog · intermediate · ~15 min

Detect a lost update

Recognise the symptom of an unsynchronised increment race.

Challenge

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.

Task

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.

Input

  • initial: starting counter value.
  • incs_a, incs_b: increments each thread performed.
  • observed: the final counter value seen.

Output

1 if observed < initial + incs_a + incs_b (updates were lost); else 0.

Example

lost_update(0, 100, 100, 150)   ->   1
lost_update(0, 100, 100, 200)   ->   0
lost_update(5, 10, 10, 20)      ->   1

Edge cases

  • observed equal to the correct total: return 0.

Input format

initial: start value; incs_a/incs_b: per-thread increments; observed: final value.

Output format

1 if observed < initial + incs_a + incs_b, else 0.

Constraints

Observed equal to the correct total is not a lost update.

Starter code

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.