I’m implementing a non-locking FIFO using a linked list.
The Enqueue of the FIFO is basically:
void Enqueue(CNode node)
{
m_tail->m_next = node;
// Do I need a memory barrier here?
m_tail = node;
}
I’m wondering if there is any need to add a memory barrier if it’s single threaded(i.e., Could compiler/processor rearrange the order of the two lines above?). And what if it’s multi-threaded(i.e., as simple as single read single writer case)?
Edit: According to here, this is a case of data anti-dependency and statements should not be reordered. So I assume CPU should always access memory in the given order. Is that right?
The compiler must not rearrange your m_tail and m_tail->next assignment such that m_tail is assigned with node before m_tail->next has been set. However, for a multi-threaded solution, you could have to worry about:
With a memory barrier, the compiler and/or the processor must complete the
m_tail->next = node;(andnode->next = NULL;) before it writes them_tail = node;. Whether this is sufficent to guarantee correct execution is not certain, it depends a bit on what the code reading at the other end does.