Lockless Linked List
For some recent work I needed to make a lockless linked list. These kind of lists are awesome because, for the most part, you can add things to the list from multiple threads with minimal cost. For my case a limitation on the needs of the list was that it only needed lockless insert, removals would be managed from a single thread. This allowed for a pretty awesomely efficient insertion function which I document here. Unfortunately this implementation is Windows specific but could probably be switched to whatever CAS your local OS uses. Enjoy.
template<typename T>
void Insert(const T \& d)
{
volatile Node<T> * current = _root;
Node<T> * n = new Node<T>(d);
volatile PVOID * ptr;
do
{
// Traverse to the end
while(current->next != NULL)
{
current = current->next;
}
ptr = (volatile PVOID *)(& (current->next));
// Attempt to swap in our new node
} while (InterlockedCompareExchangePointer(ptr, n, NULL) != NULL);
InterlockedIncrement(&_nElements);
}
Cheers, Loren
Comments
- eddie on July 25, 2010, at 05:54 PM
- chromex on August 10, 2010, at 04:42 AM