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.

Similar Reads

What is in C++11?

In multithreaded programs, multiple threads often access and modify shared data simultaneously, which can lead to data races and unpredictable behavior. solves this problem by providing atomic operations allowing threads to access and modify variables safely, without explicit locks or synchronization mechanisms....

Syntax of Atomic Variable

std::atomic var_name;...

Atomic Operations

Atomic operations are the operations that can be done on the std::atomic type and the header provides some functions to perform these atomic operations....

Examples of std::atomic

Let’s explore some examples to understand how works in practice....

Atomic Flag

...

Contact Us