我一直在研究无锁c ++ 11 fifo缓冲区。而我几乎得到了它。然而,一个小细节已经变得更好。缓冲区的头部指向:
std::shared_ptr<node<T>> m_head;
类型:
struct node
{
node(const T data)
:
data(new T(data)),
next(nullptr)
{}
std::shared_ptr<T> data;
std::shared_ptr<node<T>> next;
};
然后有产品:
void produce(const T &&data)
{
//bool indicating whether a notification should be sent after adding
bool l_notifyUponAdding;
//the new node to be added at the end of the array
std::shared_ptr<node<T>> l_newNode(new node<T>(std::forward<const T&&>(data)));
//pointer to the last node
std::shared_ptr<node<T>> l_lastNode(std::atomic_load(&m_head));
//value to compare the next of the last node with
std::shared_ptr<node<T>> l_expectedNullPointer;
//notify if this isn't the only node
l_notifyUponAdding = !l_lastNode;
if (!l_lastNode)//if there are no nodes, add this as the only node
if (std::atomic_compare_exchange_strong(&m_head, &l_expectedNullPointer, l_newNode))
return;
do
{
l_expectedNullPointer.reset();
while (l_lastNode->next)
{
l_lastNode = std::atomic_load(&l_lastNode)->next;
}
} while (!std::atomic_compare_exchange_weak(&l_lastNode->next, &l_expectedNullPointer, l_newNode));
//adding failed since another thread already did this.
l_lastNode = l_expectedNullPointer;
if (l_notifyUponAdding)
m_newDataWaiter.notify_one();
}
消费:
std::shared_ptr<T> consume(bool blockingCall = false)
{
//Check if the head is null if it is:
if (!std::atomic_load(&m_head))
{
if (blockingCall)//And this is a blocking call,
{
do
{
m_newDataWaiter.wait(m_newDataWaiterLock, [this]{return std::atomic_load(&(this->m_head)) == nullptr; });//we block until
} while (!std::atomic_load(&m_head));// the load yields a head that is not null(to avoid unnecessary calls on spurious wake ups)
}
else//And this is not a blocking call we
{
return nullptr;
}
}
//If we've found a valid head we will now try to make the node pointed to by head the new head.
std::shared_ptr<node<T>> l_poppee = atomic_load(&m_head);
std::shared_ptr<node<T>> l_newHead = atomic_load(&m_head);
//note that l_poppee gets updated if the compare exchange fails
while (l_poppee && !std::atomic_compare_exchange_weak(&m_head, &l_poppee, l_poppee->next))
{
}
if (l_poppee)
return l_poppee->data;
else
return std::shared_ptr<T>();
}
功能。
一切似乎都运作良好。不过我认为有一个缺陷。如果在执行produce
时消耗了所有节点。数据将添加到最后一个元素。即使该元素已被删除。
更确切地说,如果已执行此行:
if (std::atomic_compare_exchange_strong(&m_head, &l_expectedNullPointer, l_newNode))
加载的节点不为零。最后一个节点的下一个元素将被更改。无论是否在此期间删除节点。只要生成函数被执行,由于共享指针,节点将不会被物理删除。
但是,主指针将设置为NULL。因此,一旦退出生成函数,新节点将被删除。
是否有人碰巧知道这个问题的解决方案:)?
答案 0 :(得分:4)
通过在列表中保留虚拟节点,始终在无锁列表中解决此情况。头总是指向虚节点,它是第一个节点 清单。
当队列变空时,头部和尾部都指向虚拟节点。
您可以查看http://www.research.ibm.com/people/m/michael/podc-1996.pdf了解详细信息,这样我就不会歪曲这个概念,因为它很容易从文章中挑选出来。