小编Qza*_*aac的帖子

无锁单生产者/单消费者循环缓冲区

当我无法弄清楚为什么需要特定的内存屏障时,我一直在本网站上查看无锁的单生产者/单消费者循环缓冲区。我已经仔细阅读了数百次关于内存顺序的标准规则,但我不明白我错过了什么。

通过这种实现,只有一个可以调用该push()函数的唯一线程和另一个可以调用该函数的唯一线程pop()

这是Producer代码:

bool push(const Element& item)
{       
  const auto current_tail = _tail.load(std::memory_order_relaxed);  //(1)
  const auto next_tail = increment(current_tail);

  if(next_tail != _head.load(std::memory_order_acquire))            //(2)               
  {     
    _array[current_tail] = item;                                    //(3)
    _tail.store(next_tail, std::memory_order_release);              //(4)
    return true;
  }
  return false; // full queue
}
Run Code Online (Sandbox Code Playgroud)

这是Consumer代码:

bool pop(Element& item)
{
  const auto current_head = _head.load(std::memory_order_relaxed);    //(1)
  if(current_head == _tail.load(std::memory_order_acquire))           //(2)
    return false; // empty queue

  item = _array[current_head];                                       //(3)
  _head.store(increment(current_head), std::memory_order_release);   //(4)
  return …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading atomic lock-free c++11

6
推荐指数
1
解决办法
1811
查看次数

标签 统计

atomic ×1

c++ ×1

c++11 ×1

lock-free ×1

multithreading ×1