I'm trying to write a lock free singly linked list. Eventual consistency is not a problem (someone traversing a list which might contain incorrect items).
I think that I got the add item right (looping and Interlocked.CompareExchange
).
But I can't figure out how to remove nodes (anywhere in the list) since I have to get the previous item and them set its Next
field to the current nodes Next
field.
class Node
{
Node Next;
object Value;
}
class SinglyLinkedList
{
Root _root;
public void Add(object value)
{}
public void Remove(object value)
{}
}
i.e.
a -> b -> c
to
a -> c
Pseudo code:
Node prev;
Node node = _root;
while (node.Value != nodeValue)
{
prev = node;
node = node.Next;
}
prev.Next = node.Next;
how do I make this an atomic operation (i.e. make sure that prev.Next = node.Next
is invoked without either next or prev being removed in between by another thread)?
I could use ReaderWriterLockSlim
instead, but I found this problem interesting as I know that there exists lock free linked lists.
My concerns:
The following can happen if the current thread is suspended between the loop and the assignment:
prev
itself might have been removed by another thread.node
might have been removed by another thread.Node.Next
might have been removed
node.Next
andprev.Next
might have been changed either byAdd()
or anotherRemove()
operation. So comparing onlyprev
wont help. – Anecdotist