Multicore & Synchronization

When two threads run the code above simultaneously, the final counter can be less than 200000. Why?

int counter = 0;
// Two threads each run, at the same time:
for (int i = 0; i < 100000; i++)
    counter++;
  1. ABecause the CPU sometimes computes the addition incorrectly
  2. Bcounter++ is a separate read, add and write, and when the threads overlap one thread's increment is lost
  3. CBecause each thread's loop count is automatically halved
Show answer and explanation

Answer: B. counter++ is a separate read, add and write, and when the threads overlap one thread's increment is lost

counter++ consists of three operations: read the value from memory, add 1 and write it back. If thread A reads 100 and thread B also reads 100 before A writes back, both write 101, and two increments become one. This is a textbook data race. Using an atomic add instruction, or a lock so only one thread updates at a time, gives the correct 200000.

  • A. The CPU computes correctly.
  • B. Correct. Both add 1 to the same old value and write the same result.
  • C. The loop count does not change.
Practice this topic Back to topic

More Multicore & Synchronization questions

  1. Which describes an atomic instruction?
  2. What does the atomic CAS (compare-and-swap) instruction do?
  3. The code above doubles the shared variable counter using CAS(&p, expected, new). When does the CAS fail so the loop repeats?
  4. With an instruction pair such as RISC-V LR/SC (load-reserved / store-conditional), when does the SC fail?
  5. Which describes the ABA problem that affects lock-free data structures built with CAS?