Atomic Operations

std::atomic for lock-free programming

Interview Relevant: Performance optimization

Atomic Operations

Lock-free operations on shared data.

Code Examples

Atomic operations for lock-free programming.

cpp
1#include <atomic>
2
3atomic<int> counter(0);
4
5void increment() {
6    counter++;  // Atomic increment
7    counter.fetch_add(1);  // Same thing
8    counter.store(10);     // Atomic store
9    int val = counter.load();  // Atomic load
10}
11
12// Compare and exchange
13int expected = 5;
14int desired = 10;
15bool success = counter.compare_exchange_strong(expected, desired);
16
17// Atomic flag (always lock-free)
18atomic_flag flag = ATOMIC_FLAG_INIT;
19while (flag.test_and_set()) {
20    // Spin wait
21}
22// Critical section
23flag.clear();
24
25// Memory ordering
26counter.store(1, memory_order_relaxed);
27counter.store(1, memory_order_release);
28counter.load(memory_order_acquire);
29counter.load(memory_order_seq_cst);  // Default
30
31// Lock-free check
32if (counter.is_lock_free()) {
33    cout << "Lock-free operations available" << endl;
34}

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In