Examples of std::atomic
Let’s explore some examples to understand how <atomic> works in practice.
Example 1
std::atomic can be used with various data types for atomic operations. Let’s use it with integers:
C++
// C++ Program to illustrate the usage of <atomic> Header #include <atomic> #include <iostream> #include <thread> using namespace std; atomic< int > counter(0); // Atomic integer void increment_counter( int id) { for ( int i = 0; i < 100000; ++i) { // Increment counter atomically counter.fetch_add(1); } } int main() { thread t1(increment_counter, 1); thread t2(increment_counter, 2); t1.join(); t2.join(); cout << "Counter: " << counter.load() << std::endl; return 0; } |
Output
Counter: 200000
C++ 11 – Header
In C++11, the <atomic> header introduces a powerful mechanism for managing concurrent access to shared data in multithreaded applications. This header provides atomic types and operations that ensure safe access to variables, preventing data races and potential issues in multithreaded code. In this article, we’ll explore the concept of <atomic> in C++11, along with proper examples and comments to illustrate its usage.
Contact Us