In ultra-high-performance systems (high-frequency trading, real-time audio, game rendering engines), the latency of acquiring a mutex lock is unacceptable. C++ provides Atomic Operations via <atomic> that execute indivisibly at the CPU hardware level.
std::atomic<int>#include <iostream>
#include <atomic>
#include <thread>
#include <vector>
// Lock-free atomic integer! Zero mutexes needed!
std::atomic<int> atomicCounter{0};
void worker() {
for (int i = 0; i < 50000; ++i) {
atomicCounter.fetch_add(1, std::memory_order_relaxed); // Hardware atomic increment
}
}
int main() {
std::vector<std::jthread> threads;
for (int i = 0; i < 4; ++i) {
threads.emplace_back(worker);
}
threads.clear(); // Waits for completion
std::cout << "Atomic Counter Result: " << atomicCounter.load() << "\n"; // 200,000!
std::cout << "Is hardware lock-free: " << std::boolalpha << atomicCounter.is_lock_free() << "\n";
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Compare lock-based vs lock-free synchronization.
Spawning parallel threads.
Language evolution summary.