False Sharing and Atomic Variables

风格不统一 提交于 2019-11-29 10:16:44

A clarification: for negative consequences at least some accesses to "falsely shared" variables should be writes. If writes are rare, performance impact of false sharing is rather negligible; the more writes (and so cache line invalidate messages) the worse performance.

Even with atomics, cache line sharing (either false or true) still matters. Look for some evidence here: http://www.1024cores.net/home/lock-free-algorithms/first-things-first. Thus, the answer is - yes, placing atomic variables used by different threads to the same cache line may make application slower compared to placing them to two different lines. However, I think it will be mostly unnoticed, unless the app spends a significant portion of its time updating these atomic variables.

If you use atomic variables with the strongest consistency requirements, a full memory barrier, the effect of false sharing will probably not be noticeable. For such an access the performance of an atomic operation is basically limited by the memory access latency. So things are slow anyhow, I don't think they would get much slower in the presence of false sharing.

If you have other less intrusive memory orderings the performance hit by the atomics itself may be less, and so the impact of false sharing might be significant.

In total, I would first look at the performance of the atomic operation itself before worrying about false sharing for such operations.

will putting atomic variables in the same cache line make application slower than not putting them in the same cache line?

False sharing of "atomic" variables could lead to performance problems (whether or not it will lead to such problems depends on a lot of things).

Let's say you have two cores, A and B, and each operates on its own variable. Let's call these variables a and b respectively.

A has a in its cache, and B has b in its cache.

Consider what happens when A increments a.

  • if a and b share a cache line, B's copy of b will get invalidated, and its next access to b will incur a cache miss.
  • if a and b don't share a cache line, there's no impact on B as far as its cached copy of b is concerned.

This happens regardless of whether a and b are "atomic".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!