Non-atomic compound operations
Review this C++ statistics accumulator shared across threads.
Two of these three updates are broken under concurrency. Which two and why?
What a strong answer looks like
Separate real bugs from style. Rank issues by severity, point at the root cause rather than the symptom, and suggest a concrete fix, specific and kind.
0:00 of about 25 min
Mark a line and say what kind of problem it is.0 findings
1struct Stats {
2 std::atomic<long> count{0};
3 std::atomic<double> sum{0.0};
4 long max = 0; // plain
5
6 void record(double x) {
7 count.fetch_add(1, std::memory_order_relaxed);
8 sum.store(sum.load() + x); // (1)
9 if ((long)x > max) max = (long)x; // (2)
10 }
11};
Which questions mattered is sealed until you submit. Telling you now would just be handing over the edge cases.
Run or narrate your approach, then ask the coach.