Skip to content

Instantly share code, notes, and snippets.

@bw2012
Created July 11, 2018 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bw2012/67f89281f082e91bf9d6b14ccd09db5f to your computer and use it in GitHub Desktop.
Save bw2012/67f89281f082e91bf9d6b14ccd09db5f to your computer and use it in GitHub Desktop.
lock free test
#include <stdio.h>
#include <atomic>
template<typename V>
class LockFreeList {
struct Node {
V value;
std::shared_ptr<Node> next;
Node(const V& value) : value(value), next(nullptr) {}
};
//std::atomic<std::shared_ptr<Node>> first; // waiting for C++20
std::shared_ptr<Node> first;
public:
void push_front(const V& value) {
auto new_node = std::make_shared<Node>(value);
new_node->next = std::atomic_load(&first);
while(!std::atomic_compare_exchange_weak(&first, &new_node->next, new_node));
}
V pop_front() {
auto node = std::atomic_load(&first);
while (node && !std::atomic_compare_exchange_weak(&first, &node, node->next));
return std::move(node->value);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment