Skip to content

Instantly share code, notes, and snippets.

@ChaosEngine
Created July 20, 2018 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChaosEngine/f378f3ac17c39dc62b4f65d834cd0387 to your computer and use it in GitHub Desktop.
Save ChaosEngine/f378f3ac17c39dc62b4f65d834cd0387 to your computer and use it in GitHub Desktop.
Parallel scheme to partition long calculation
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