gpt4 book ai didi

c++ - 来自 Boost.Atomic 示例的无等待队列崩溃

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:29:04 25 4
gpt4 key购买 nike

我一直在寻找使用原子的无等待队列的 C++ 实现,并找到了 Boost.Atomic 示例:

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

}

Example at boost official site

我已将 boost 替换为 std 并使用 MSVC 2012 进行编译。它崩溃并在控制台中显示下一条消息:

Assertion failed: _Order2 != memory_order_release, file c:\program files (x86)\m
icrosoft visual studio 11.0\vc\include\xxatomic, line 742

当我编译原始 boost 时,它运行时崩溃。

它是 Boost.Atomic 中的错误还是原子的 MSVC 实现中的错误?

最佳答案

它看起来像是 MSVC 实现中的错误。断言失败,因为 Order2memory_order_release。但是,如前所述here (与 C++ 标准相同)(强调我的):

The 3-parameter overload is equivalent to the 4-parameter overload with success_order==order, and failure_order==order, except that if order is std::memory_order_acq_rel, then failure_order is std::memory_order_acquire, and if order is std::memory_order_release then failure_order is std::memory_order_relaxed.

换句话说,Order2 必须是 std::memory_order_relaxed 对于您的情况下的 4 参数重载,因为您通过了 memory_order_release 作为order。 MSVC 的实现不是这种情况,这是一个错误。如果可能,请将其报告为错误。

关于c++ - 来自 Boost.Atomic 示例的无等待队列崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14802378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com