January 2020
Intermediate to advanced
454 pages
11h 25m
English
In this recipe, we will learn how to use atomic data types in C++. Atomic data types provide the ability to read and write simple data types (that is, a Boolean or integer) without the need for thread synchronization (that is, the use of std::mutex and friends). To accomplish this, atomic data types are implemented using special CPU instructions that ensure when an operation is executed, it is done so as a single, atomic operation.
For example, incrementing an integer can be written as follows:
int i = 0;auto tmp = i;tmp++;i = tmp; // i == 1
An atomic data type ensures that this increment is executed such that no other attempts to increment the integer simultaneously can interleave, and therefore result in corruption. ...