Using atomic types
The thread library provides support for managing threads and synchronizing access to shared data with mutex and locks. The standard library provides support for the complementary, lower-level atomic operations on data, that is, indivisible operations that can be executed concurrently from different threads on shared data without the risk of producing race conditions and without the use of locks. The support it provides includes atomic types, atomic operations, and memory synchronization ordering. In this recipe, we will see how to use some of these types and functions.
Getting ready
All the atomic types and operations are defined in the std
namespace in the <atomic>
header.
How to do it...
The following is a series of typical operations that use atomic types:
- Use the
std::atomic
class template to create atomic objects that support atomic operations, such as loading, storing, or performing arithmetic or bitwise operations:
std::atomic<int> counter {0}; ...