c++多线程进阶(6): 采用精细粒度的锁和条件变量的threadsafe_queue

进阶(5)里的实现缺点是用唯一的互斥保护整个数据结构, 支持的并发程度受限

开始研究采用精细粒度的锁和条件变量实现线程安全的队列容器, 此时不用stl容器


自行实现的queue

示例

注意head和tail的声明区别

unique_ptr<node> head;

node *tail;

template<typename T>
class queue
{
    struct node
    {
        T data;
        unique_ptr<node> next;

        node(T data_) : data(move(data_))
        {}
    };

    unique_ptr<node> head;          //1
    node *tail;                     //2
public:
    queue() : tail(nullptr)
    {}

    queue(const queue &other) = delete;

    queue &operator=(const queue &other) = delete;

    shared_ptr<T> try_pop()
    {
        if (!head)
        {
            return shared_ptr<T>();
        }
        shared_ptr<T> const res(make_shared<T>(move(head->data)));
        unique_ptr<node> const old_head = move(head);
        head = move(old_head->next);        //3
        if (!head)
        {
            tail = nullptr;
        }
        return res;
    }

    void push(T new_value)
    {
        unique_ptr<node> p(new node(move(new_value)));
        node *const new_tail = p.get();
        if (tail)
        {
            tail->next = move(p);       //4
        }
        else
        {
            head = move(p);             //5
        }
        tail=new_tail;          //6
    }
};

单线程下运行良好

其中有两项数据head和tail(1处2处),  原则上可以使用两个互斥分别保护head指针和tail指针

然而这样做后:

push()会同时操作head和tail指针( 5处和6处), 于是该函数就需要将两个锁都锁住,

严重的问题在于,若队列只有1项数据, head和tail指会向同一节点(head==tail)

此时push()更新tail->next, try_pop()读取head->next

若没有读取head和tail的数据,就无法辨别是否是同一结点,

于是push(),  try_pop()并发执行中会无意锁住同一互斥, 和以前比并无改善

同过分离数据实现并发

把数据和指针分开

预设1个不含数据的虚位节点, 如果队列为空, tail和head两个指针都不是NULL值, 而是指向虚位节点

 缺点: 为了容纳虚伪节点, 需要通过指针间接存储数据, 额外增加一个访问层级

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值