#include #include #include #include template class stack { private: struct node { std::shared_ptr data; std::shared_ptr next; node(T const& data_) : data(std::make_shared(data_)) {} }; std::shared_ptr head; public: void push(T const& data) { std::shared_ptr const new_node = std::make_shared(data); new_node->next = std::atomic_load(head); while (!std::atomic_compare_exchange_weak(&head, &new_node->next, new_node)); } std::shared_ptr pop() { std::shared_ptr old_head = std::atomic_load(head); while (old_head && !std::atomic_compare_exchange_weak(&head, &old_head, old_head->next)); return old_head ? old_head->data : std::shared_ptr(); } }; void push(stack* s) { for (int i = 0; i < 10; ++i) { printf("pushing %d\n", i); s->push(i); } } void pop(stack* s) { int count = 0; std::shared_ptr e; while (count < 10) { if (e = s->pop()) { printf("popping %d\n", *e); ++count; } } } int main() { std::shared_ptr sp = std::make_shared(1); //printf("std::atomic_is_lock_free(std::shared_ptr): %d\n", // std::atomic_is_lock_free(&sp)); stack s; std::thread t1(push, &s); std::thread t2(pop, &s); t1.join(); t2.join(); return 0; }