I need to traverse a tree quickly, and I would like to do it in parallel. I\'d rather use the parallel extensions than manually spin up a bunch of threads.
My current co
Perhaps using a List or Array instead of queue would help. Also use another List/Array to populate the next nodes to visit. You won't be processing list that until you finish the entire width first anyway. Something like this:
List todoList = new List();
todoList.Add(node);
while (todoList.Count > 0)
{
// we'll be adding next nodes to process to this list so it needs to be thread-safe
// or just sync access to a non-threadsafe list
// if you know approx how many nodes you expect, you can pre-size the list
ThreadSafeList nextList = new ThreadSafeList();
//todoList is readonly/static so can cache Count in simple variable
int maxIndex = todoList.Count-1;
// process todoList in parallel
Parallel.For(0, maxIndex, i =>
{
// if list reads are thread-safe then no need to sync, otherwise sync
Node x = todoList[i];
//process x;
// e.g. do somehting, get childrenNodesToWorkOnNext, etc.
// add any child nodes that need to be processed next
// e.g. nextList.add(childrenNodesToWorkOnNext);
});
// done with parallel processing by here so use the next todo list
todoList = nextList;
)