Benutzer:MovGP0/Parallel/Loops
aus Wikipedia, der freien Enzyklopädie
< Benutzer:MovGP0 | Parallel
MovGP0 | Über mich | Hilfen | Artikel | Weblinks | Literatur | Zitate | Notizen | Programmierung | MSCert | Physik |
Parallel Loops
Methods
Loop State
Loop Cancellation Token
int n = ...;
var token = cancellationTokenSource.Token;
var options = new ParallelOptions {
CancellationToken = token
};
try
{
Parallel.For(0, n, options, i => {
if(token.IsCancellationRequested)
{
return;
}
// do some work
});
}
catch(OperationCancelledException)
{
// ...
}
Exception Handling
Partitioner
int n = ...;
var result = double[n];
Parallel.ForEach(Partitioner.Create(0, n), range =>
{
foreach(var index in range)
{
// ...
}
});
Degree of Parallelism
var n = ...;
var options = new ParallelOptions() {
MaxDegreeOfParallelism = 2
};
Parallel.For(0, n, options, i => {
// ...
});
enumerable.AsParallel().WithDegreeOfParallelism(n)
Task-Local State
int numberOfSteps = ...;
var result = new double[numberOfSteps];
var partitioner = Partitioner.Create(0, numberOfSteps);
var options = new ParallelOptions { /* ... */ };
Parallel.ForEach(partitioner, options, () => new Random(MakeRandomSeed()), (range, loopState, localRandom) =>
{
foreach(var index in range)
{
result[i] = localRandom.NextDouble();
return localRandom;
}
}, localRandom => { /* finally */ });
Note:
Task Scheduler
int n = ...;
var taskScheduler = new TaskScheduler(/* ... */);
var options = new ParallelOptions
{
TaskScheduler = taskScheduler
};
Parallel.For(0, j, options, i => { /* ... */});
AntipatternsStep size other than one
Hidden loop body dependencies
Small loop bodies with few iterations
Processor oversubscription and undersubscription
Parallel.ForEach on PLINQ Query
Duplicates in Input Enumeration
Design Notes
|