用shared_ptr实现的无锁栈

文章介绍了一个使用C++实现的线程安全栈,该栈利用shared_ptr管理节点及数据,并通过atomic<int>保证在多线程环境下pop操作的正确计数。在测试中,使用了100个push线程和2个pop线程进行并发操作,确保了栈的正确功能。
摘要由CSDN通过智能技术生成

基于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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值