Avoid False Sharing With C++11 alignas Keyword

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: