counter++ is three steps for the CPU: load the counter into a register, add 1, and store the register. When two threads interleave these steps, one update can overwrite another.
What to build
Replay a schedule of thread steps on a shared counter and report how many updates were lost.
Requirements
- The counter starts at 0. Each of the
tthreads must add 1 to the counterktimes. One increment is three steps in this order: load the counter into the thread's own register, add 1 to the register, store the register in the counter. - The schedule lists which thread runs next, one step at a time. A step for a thread that has finished all its increments does nothing.
- Print
counter C(the final value),increments I(the number of stores that happened), andlost L(IminusC).
Input
The first line has t (1 ≤ t ≤ 4), k (1 ≤ k ≤ 5) and s (1 ≤ s ≤ 60). The second line has s thread numbers, from 1 to t.
Output
Three lines: counter C, increments I, lost L.
Constraints
The schedule may end before all threads finish; only the steps given are run.
Example
Input:
2 1 6
1 2 1 2 1 2
Output:
counter 1
increments 2
lost 1
Why it works
Two threads that both load before either stores end up writing the same new value, so one increment disappears. The result depends on the schedule alone, which is why races are so hard to reproduce: the same program gives different answers on different runs.
Examples
2 1 6 1 2 1 2 1 2
counter 1 increments 2 lost 1
2 1 6 1 1 1 2 2 2
counter 2 increments 2 lost 0
Hints
Hint 1
Give each thread its own pc (steps done) and reg. The step a thread takes next is pc % 3: 0 is the load, 1 the add, 2 the store.
Hint 2
A thread that has done 3 times k steps is finished: its steps in the schedule do nothing.
Hint 3
Count a finished increment each time a store happens. lost = increments finished - counter.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
int main(void) {
int t, k, s, who, counter = 0, stores = 0;
int pc[5] = {0}, reg[5] = {0};
scanf("%d %d %d", &t, &k, &s);
for (int i = 0; i < s; i++) {
scanf("%d", &who);
if (pc[who] >= 3 * k) continue;
int step = pc[who] % 3;
if (step == 0) reg[who] = counter;
else if (step == 1) reg[who] = reg[who] + 1;
else {
counter = reg[who];
stores++;
}
pc[who]++;
}
(void)t;
printf("counter %d\n", counter);
printf("increments %d\n", stores);
printf("lost %d\n", stores - counter);
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step