Multicore & Synchronization

False sharing occurs with an array of per-thread counters such as "long cnt[8];". What is the most suitable fix?

  1. AChange the counters from long to int to shrink the array
  2. BAdd padding or alignment so that each counter sits in its own cache line
  3. CIncrease the number of threads to spread out the waiting
Show answer and explanation

Answer: B. Add padding or alignment so that each counter sits in its own cache line

With 8-byte longs, eight counters fit in a single 64-byte line, and all threads fight over it. Padding so each counter sits 64 bytes apart, or aligning a struct to the cache-line size, gives each thread its own line. Another effective approach is for each thread to count in a local variable and add to the shared location only once at the end.

  • A. Shrinking packs them even more tightly into one line.
  • B. Correct. Separating the lines stops the bouncing.
  • C. More threads would increase the bouncing.
Practice this topic Back to topic

More Multicore & Synchronization questions

  1. Which describes a data race?
  2. When two threads run the code above simultaneously, the final counter can be less than 200000. Why?
  3. Which describes an atomic instruction?
  4. What does the atomic CAS (compare-and-swap) instruction do?
  5. The code above doubles the shared variable counter using CAS(&p, expected, new). When does the CAS fail so the loop repeats?