Multicore & Synchronization
False sharing occurs with an array of per-thread counters such as "long cnt[8];". What is the most suitable fix?
- AChange the counters from long to int to shrink the array
- BAdd padding or alignment so that each counter sits in its own cache line
- 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.