CppMem: Non-Atomic Variables

This lesson gives an overview of non-atomic variables used in the context of CppMem.

Using the run button immediately shows that there is a data race. To be more precise, it has two data races. Neither the access to the variable x nor to the variable y are protected. As a result, the program has undefined behavior. In C++ jargon, this means that the program has the so-called catch fire semantic; therefore, all results are possible. Your PC can even catch fire.

So, we are not able to draw conclusions about the values of x and y.

Guarantees for int variables

Most of the mainstream architectures guarantee that access to an int variable is atomic as long as the int variable is aligned naturally. Naturally aligned means that the int variable on a 32-bit architecture must have an address divisible by 4; On a 64-bit architecture, it’s divisible by 8. I mention this so explicitly because you can adjust the alignment of your data types with C++.

I have to emphasize that I’m not advising you to use an int as an atomic int. I only want to point out that the compiler guarantees more in this case than the C++11 standard. If you rely on the compiler guarantee, your program will not be compliant with the C++ standard and, therefore, may break in the future.

This was my reasoning. Now we should have a look at what CppMem will report about the undefined behavior of the program. As it stands, CppMem allows me to reduce the program to its bare minimum.

Get hands-on with 1200+ tech skills courses.