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 and the array aligned to a 64-byte boundary, the eight counters fit in a single 64-byte line, and all threads fight over it. Even unaligned, they span only two lines, so the contention remains. 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.