Types of Parallelism in C#
C# supports two main models of parallelism:
We can limit the degree of parallelism like this:
var options = new ParallelOptions() {
MaxDegreeOfParallelism = 2 };
Parallel.For(0, n, options, i =>
{
fibs[i] = Fib(i);
});
Parallel loops have two ways to break or stop a loop
instead of just one.
C# supports two main models of parallelism:
- Data parallelism: where an operation is applied to each element in a collection.
- Task parallelism: where independent computations are executed in parallel.
int n = ...
for (int i = 0; i<=n; i++)
{
// ...
});
A parallel for loop in C#:
int n = ...
Parallel.For(0, n, i =>
{
// ...
});
- The language construct for is translated into a(higher-order) function Parallel.For.
- The argument to Parallel.For is an anonymous method, specifying the code to be performed in each loop iteration.
- The arguments to this anonymous method are the start value, the end value and the iteration variable.
We can limit the degree of parallelism like this:
var options = new ParallelOptions() {
MaxDegreeOfParallelism = 2 };
Parallel.For(0, n, options, i =>
{
fibs[i] = Fib(i);
});
Parallel loops have two ways to break or stop a loop
instead of just one.
- Parallel break, loopState.Break(), allows all steps with indices lower than the break index to run before terminating the loop.
- Parallel stop, loopState.Stop(), terminates the loop without allowing any new steps to begin.
No comments:
Post a Comment