【发布时间】:2016-09-16 18:37:51
【问题描述】:
在 Anthony Williams 的《C++ Concurrency in Action》一书中,第 7.2.1 节列出了无锁堆栈实现:
template <typename T>
class lock_free_stack {
struct node {
shared_ptr<T> data_;
node* next_;
node(const T& data) : data_(make_shared(data)) {}
};
atomic<node*> head_;
public:
void push(const T& data)
{
node* new_node = new node(data);
new_node->next_ = head_.load();
while(!head.compare_exchange_weak(new_node->next_, new_node));
}
shared_ptr<T> pop()
{
node* old_head = head_.load();
while (old_head &&
!head_.compare_exchange_weak(old_head, head_->next_));
return old_head ? old_head->data_ : shared_ptr<T>();
}
};
然后在第 7.2.2 节中,作者说“......在 pop() 中,我们选择泄漏节点以避免竞争条件,即一个线程删除一个节点而另一个线程仍然持有指向它的指针它即将取消引用。”
1) 我不明白为什么会发生这种情况以及为什么下面的 pop() 函数会导致竞态条件:
shared_ptr<T> pop()
{
node* old_head = head_.load(); // (1)
while (old_head &&
!head_.compare_exchange_weak(old_head, head_->next_)); // (2)
shared_ptr<T> res; // (3)
if (old_head) {
res.swap(old_head->data);
delete old_head;
return res;
} else {
return {};
}
}
2) 为什么多个线程同时调用pop(),'old_head'变量在第(3)行之后可以指向同一个节点对象?
【问题讨论】:
标签: c++ c++11 concurrency atomic race-condition