Lock-Free Atomic Types (std::atomic)

🔴 Advanced

📖 Definition

Provided in <atomic>, std::atomic<T> wraps primitive types into lock-free atomic variables that execute read-modify-write operations directly using hardware CPU instructions, eliminating mutex lock overhead for simple counters and flags.

💡 Code Example

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

std::atomic<int> atomicCounter{0};

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

int main() {
    std::thread t1(task), t2(task);
    t1.join(); t2.join();
    std::cout << "Atomic Counter: " << atomicCounter << "\n";
    return 0;
}