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++;
- ABecause the CPU sometimes computes the addition incorrectly
- Bcounter++ is a separate read, add and write, and when the threads overlap one thread's increment is lost
- 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.