example4_lock-free_stack.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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <atomic>
#include <memory>
#include <iostream>

template<typename T>
class lock_free_stack {
    struct node {
        T data;
        node* next;
        node(const T& data) : data(data), next(nullptr) {}
    };

    std::atomic<node*> head;

public:
    lock_free_stack() : head(nullptr) {}

    void push(const T& data) {
        node* new_node = new node(data);
        new_node->next = head.load(std::memory_order_relaxed);
        while (!head.compare_exchange_weak(new_node->next, new_node,
                                           std::memory_order_release,
                                           std::memory_order_relaxed));
    }

    bool pop(T& result) {
        node* old_head = head.load(std::memory_order_relaxed);
        while (old_head && !head.compare_exchange_weak(old_head, old_head->next,
                                                       std::memory_order_acquire,
                                                       std::memory_order_relaxed));
        if (old_head) {
            result = old_head->data;
            delete old_head;
            return true;
        }
        return false;
    }
};

int main() {
    lock_free_stack<int> stack;

    stack.push(1);
    stack.push(2);
    stack.push(3);
    stack.push(4);
    stack.push(5);
    stack.push(6);

    int value;
    while (stack.pop(value)) {
        std::cout << "Popped: " << value << std::endl;
    }

    return 0;
}
Back to atomic