Multicore & Synchronization
Which describes a data race?
- AMultiple threads only read the same variable at the same time
- BOne thread writes the same variable twice in a row
- CMultiple threads access the same variable at the same time without synchronization, and at least one access is a write
Show answer and explanation
Answer: C. Multiple threads access the same variable at the same time without synchronization, and at least one access is a write
A data race occurs when the order of reads and writes to one location is not fixed by synchronization, so the result depends on the order in which they happened to run. Because it appears or not depending on timing, it is a hard bug to find by testing. In C and C++, a program with a data race has undefined behavior. Locks or atomic variables must be used to establish an order.
- A. Reading alone changes nothing, so there is no problem.
- B. Within one thread the order is well defined.
- C. Correct. It makes results vary from run to run.