我正在寻找使用原子的无等待队列的C++实现,并找到了Boost。原子示例:
template<typename T>
class waitfree_queue {
public:
struct node {
T data;
node * next;
};
void push(const T &data)
{
node * n = new node;
n->data = data;
node * stale_head = head_.load(boost::memory_order_relaxed);
do {
n->next = stale_head;
} while (!head_.compare_exchange_weak(stale_head, n, boost::memory_order_release));
}
node * pop_all(void)
{
T * last = pop_all_reverse(), * first = 0;
while(last) {
T * tmp = last;
last = last->next;
tmp->next = first;
first = tmp;
}
return first;
}
waitfree_queue() : head_(0) {}
// alternative interface if ordering is of no importance
node * pop_all_reverse(void)
{
return head_.exchange(0, boost::memory_order_consume);
}
private:
boost::atomic<node *> head_;
};
int main() {
// pop elements
waitfree_queue<int>::node * x = q.pop_all()
while(x) {
X * tmp = x;
x = x->next;
// process tmp->data, probably delete it afterwards
delete tmp;
}
}
boost官方网站上的示例
我用std代替了boost,并用MSVC 2012编译。它与控制台中的下一条消息崩溃:
Assertion failed: _Order2 != memory_order_release, file c:program files (x86)m
icrosoft visual studio 11.0vcincludexxatomic, line 742
当我编译原始boost时,它会崩溃。
是Boost中的bug吗。原子还是在MSVC中实现原子?
它看起来像是MSVC实现中的一个bug。断言失败,因为Order2
是memory_order_release
。然而,正如这里所指出的(这与C++标准相同)(强调矿):
3参数过载等效于4参数过载success_order==order,failure_order==order,除非order为std::memory_order_aq_rel,则failure_order为std::memory_order_aquire,并且如果订单为std::memory_order_release则failureorder为std::memoryorder_relaxed。
换句话说,在您的情况下,对于4参数重载,Order2
必须是std::memory_order_relaxed
,因为您将memory_order_release
传递为order
。在MSVC的实现中并不是这样,它是一个bug。如果可能的话,请将其作为错误报告。