Created
July 11, 2018 20:49
-
-
Save bw2012/67f89281f082e91bf9d6b14ccd09db5f to your computer and use it in GitHub Desktop.
lock free test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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