-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlisting_7.10.cpp
More file actions
36 lines (35 loc) · 962 Bytes
/
Copy pathlisting_7.10.cpp
File metadata and controls
36 lines (35 loc) · 962 Bytes
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
template<typename T>
class lock_free_stack
{
private:
struct node
{
std::shared_ptr<T> data;
std::experimental::atomic_shared_ptr<node> next;
node(T const& data_):
data(std::make_shared<T>(data_))
{}
};
std::experimental::atomic_shared_ptr<node> head;
public:
void push(T const& data)
{
std::shared_ptr<node> const new_node=std::make_shared<node>(data);
new_node->next=head.load();
while(!head.compare_exchange_weak(new_node->next,new_node));
}
std::shared_ptr<T> pop()
{
std::shared_ptr<node> old_head=head.load();
while(old_head && !head.compare_exchange_weak(
old_head,old_head->next.load()));
if(old_head) {
old_head->next=std::shared_ptr<node>();
return old_head->data;
}
return std::shared_ptr<T>();
}
~lock_free_stack(){
while(pop());
}
};