进阶(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值, 而是指向虚位节点
缺点: 为了容纳虚伪节点, 需要通过指针间接存储数据, 额外增加一个访问层级