Created
March 30, 2014 23:07
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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