When two threads are frequently accessing and updating the 2 different but independent variables on the same cacheline, cache thrashing occurs as a result because when the thread updates its variable, the thread on another CPU core has its cacheline invalidated and have to fetch from the main memory again even though it is not interested in the updated variable. This is called false sharing. With C++11’s alignas keyword, the variable alignment can be set to be 64 bytes which is a common cacheline size to avoid false sharing.
alignas(64) int foo; alignas(64) int bar;
Leave a Reply