Multicore & Synchronization

Which describes a data race?

  1. AMultiple threads only read the same variable at the same time
  2. BOne thread writes the same variable twice in a row
  3. 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.
Practice this topic Back to topic

More Multicore & Synchronization questions

  1. When two threads run the code above simultaneously, the final counter can be less than 200000. Why?
  2. Which describes an atomic instruction?
  3. What does the atomic CAS (compare-and-swap) instruction do?
  4. The code above doubles the shared variable counter using CAS(&p, expected, new). When does the CAS fail so the loop repeats?
  5. With an instruction pair such as RISC-V LR/SC (load-reserved / store-conditional), when does the SC fail?