How do I use atomics and memory order?

This article provides an overview of using atomics and memory ordering in C++. It explains how atomics work and the various memory order options available, along with practical examples to illustrate their use.
C++, atomics, memory ordering, multithreading, concurrency

#include <iostream>
#include <atomic>
#include <thread>

// Shared variable
std::atomic counter(0);

// Function to increment counter
void increment() {
    for (int i = 0; i < 1000; ++i) {
        counter.fetch_add(1, std::memory_order_seq_cst); // Use sequential consistency
    }
}

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

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

    std::cout << "Final counter value: " << counter.load() << std::endl; // Should be 2000
    
    return 0;
}
    

C++ atomics memory ordering multithreading concurrency