基于shared_ptr与atimoc的栈,中间用原子int对pop元素进行计数 用100个push线程与2个pop线程测试过了
#include<vector>
template<typename T>
class shared_stack{
private:
struct node{
shared_ptr<T> data;
shared_ptr<node> next;
node(T const &data_):data(make_shared<T>(data_)){}
};
shared_ptr<node> head;
atomic<int> size;
public:
void push(T const&value){
shared_ptr<node> const new_node = make_shared<node>(value);
new_node->next = atomic_load(&head);
while(!atomic_compare_exchange_weak(&head,&new_node->next,new_node))
;
size++;
}
shared_ptr<T> pop(){
shared_ptr<node> old_head = atomic_load(&head);
while(old_head && !std::atomic_compare_exchange_weak(&head,&old_head,atomic_load(&old_head->next)))
;
if(old_head){
size--;
atomic_store(&old_head->next, shared_ptr<node>());
return old_head->data;
}
return shared_ptr<T>();
}
~shared_stack(){
while(pop())
;
}
int size_(){
return this->size.load();
}
};
template<typename T>
void push(shared_stack<T>& stack){
for (int i = 0; i < 1000;i++)
stack.push(i);
}
int main(){
shared_stack<int> stack;
vector<thread> ts;
for (int i = 0; i < 100;i++)
ts.push_back(thread(&push<int>, ref(stack)));
for (auto &x:ts)
x.join();
thread pop([&](shared_stack<int> &)
{
while(stack.size_()>=10){
int mid = *stack.pop();
if(mid )
cout <<mid<<" ";
} },
ref(stack));
thread pop2([&](shared_stack<int> &)
{
while(stack.size_()>=10){
int mid = *stack.pop();
if(mid )
cout <<mid<<" ";
} },
ref(stack));
pop.join();
pop2.join();
return 0;
}