example2_compare_and_swap.cpp

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

std::atomic<int> counter(0);

void increment_if_zero() {
    int expected = 0;
    if (counter.compare_exchange_strong(expected, 100)) {
        std::cout << "Counter was zero, updated to 100" << std::endl;
    } else {
        std::cout << "Counter was not zero, value is " << counter.load() << std::endl;
    }
}

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

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

    std::cout << "Final counter value: " << counter << std::endl;

    return 0;
}
Back to std_atomic