Skip to content

Instantly share code, notes, and snippets.

@davidfowl
Created March 30, 2014 23:07
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save davidfowl/9881486 to your computer and use it in GitHub Desktop.
Specialized lock free linked list with 2 operations, Add and GetListAndClear. Useful for implementing batching.
public class FastLinkedList<T>
{
private Node Head;
public void Add(T value)
{
var node = new Node();
node.Value = value;
while (true)
{
var oldHead = Head;
node.Next = Head;
node.Count = 1 + (oldHead == null ? 0 : oldHead.Count);
if (Interlocked.CompareExchange(ref Head, node, oldHead) == oldHead)
{
break;
}
}
}
public IList<T> GetAndClear()
{
var node = Interlocked.Exchange(ref Head, null);
var values = new T[node.Count];
int at = node.Count - 1;
while (node != null)
{
values[at--] = node.Value;
node = node.Next;
}
return values;
}
private class Node
{
public T Value;
public Node Next;
public int Count;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment