Created
July 20, 2018 21:54
-
-
Save ChaosEngine/f378f3ac17c39dc62b4f65d834cd0387 to your computer and use it in GitHub Desktop.
Parallel scheme to partition long calculation
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
async Task<double> ComputeStuffAsync(CancellationToken token) | |
{ | |
var tsk = Task.Run(() => | |
{ | |
var sum = 0.0; | |
int DOP = 4; | |
Parallel.For(0, DOP - 1, new ParallelOptions { MaxDegreeOfParallelism = DOP, CancellationToken = token }, | |
// Initialize the local states | |
() => (double)0.0, | |
// Accumulate the thread-local computations in the loop body | |
(thread, loop, localState) => | |
{ | |
long from = 1 + (thread * 100 * 1000 * 1000); | |
long to = ((thread + 1) * 100 * 1000 * 1000); | |
var computed = Calc(from, to); | |
return localState + computed; | |
}, | |
// Combine all local states | |
localState => Interlocked.Exchange(ref sum, localState) | |
); | |
return sum; | |
}, token); | |
return await tsk; | |
double Calc(long from, long to) | |
{ | |
double sum = 0; | |
for (long i = from; i < to; i++) | |
sum += Math.Sqrt(i); | |
return sum; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment