Skip to content

Instantly share code, notes, and snippets.

@JohnMGant
Created December 9, 2020 21:00
Show Gist options
  • Select an option

  • Save JohnMGant/bf0bfa5f21c904ca0d306c41864d6fe5 to your computer and use it in GitHub Desktop.

Select an option

Save JohnMGant/bf0bfa5f21c904ca0d306c41864d6fe5 to your computer and use it in GitHub Desktop.
internal class ParallelAdder : IIntegerAdder
{
public int Add(int[] values)
{
var queue = new ConcurrentQueue<int>(values);
int overallSum = 0;
Action addFromQueue = () =>
{
int localSum = 0;
while (queue.TryDequeue(out int localValue))
{
localSum += localValue;
}
Interlocked.Add(ref overallSum, localSum);
};
Parallel.Invoke(addFromQueue, addFromQueue, addFromQueue, addFromQueue);
return overallSum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment