Using atomic data types

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. How this is done by the CPU is out of the scope of this book. That's because this is extremely complicated in modern, super-scalar, pipelined CPUs that support the execution of instructions in parallel, out-of-order, and speculatively on multiple cores and sockets.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset