CodePark/ questions / Concurrency primitives & race conditions
START PRACTICINGPRACTICE
Backend question · OS, networking & Linux › Concurrency primitives & race conditions

Two threads each run counter++ one million times on a shared integer with no locking. What is the final value of counter?

Often less than 2,000,000, because ++ is a read-modify-write and updates can be lost

The result is often less than 2,000,000. counter++ is three steps: read the value, add one, write it back. This is a read-modify-write. If both threads read the same value before either one writes, one increment is lost. So the result changes between runs and is usually below 2,000,000.

"Exactly 2,000,000, because
++ is a single operation" is wrong: ++ is not a single step. "Exactly 1,000,000" is also wrong: the threads do not overwrite each other every time. The order in which their steps mix is unpredictable. "The program always crashes" is wrong: lost updates give a wrong number, not a crash.

An atomic increment or a mutex makes the result exactly 2,000,000.