1

在使用无锁队列实现来存储指向一组预分配缓冲区的指针时,我发现一些缓冲区仍在由一个线程写入,而另一个线程开始使用它。我已经用内存屏障保护了缓冲区的写入和读取,但它似乎不起作用。

线程 1 循环:

auto b=queue.AcquireBuffer();

for (int x=0;x<BUF_SIZE;x++)
{
    b->GetData()[x]=-999999999990;          // A
}
atomic_thread_fence(memory_order_seq_cst)   // edit: still does not work
high_resolution_clock::time_point tp=high_resolution_clock::now();
b->GetData()[1]=1+time_diff(tp,tp_normal);  // B

atomic_thread_fence(memory_order_seq_cst);
queue.PushBuffer(b);

线程 2 循环:

auto bb=queue.Peak();

atomic_thread_fence(memory_order_seq_cst);

if ((bb[0])->GetData()[1] < 0) {
    std::cout<<"fail"<<endl;
    ready=true;
    while (1) {}
}

queue.Pop();

一段时间后我得到“失败”作为输出,这意味着线程 2 看到 A 和 B 块的无序执行。我希望这些事情有条不紊地发生。我该如何解决?(假设 time_diff 总是返回一个正数)

队列来源:http ://pastebin.com/raw.php?i=PFBzMPPF

完整来源:https ://docs.google.com/file/d/0B8gY3VVJJr1IMktobnhYelBva2c/edit?usp=docslist_api

4

0 回答 0