example1_basic_usage.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <atomic>
#include <thread>

std::atomic<int> counter(0);  // Atomic integer

void increment() {
    for (int i = 0; i < 1000; ++i) {
        ++counter;  // Atomic increment
    }
}

int main() {
    std::thread t1(increment);
    std::thread t2(increment);

    t1.join();
    t2.join();

    std::cout << "Final counter value: " << counter << std::endl;  // Should be 2000

    return 0;
}
Back to std_atomic