Created
December 9, 2020 21:00
-
-
Save JohnMGant/bf0bfa5f21c904ca0d306c41864d6fe5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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