I can change my loop
for (int i = 0; i < something; i++)
to:
Parallel.For(0, something, i =>
But how to do this with this loop?:
for (i = 3; i <= something / 2; i = i + 2)
Thanks for answers.
Can any for loop be made parallel? No, not any loop can be made parallel. Iterations of the loop must be independent from each other. That is, one cpu core should be able to run one iteration without any side effects to another cpu core running a different iteration.
In a parallel loop, the parallel processors execute the same code region, namely, the loop body, but with different data. Thus, parallel loops are a special kind of SPMD programming. Typically, parallel loops are used within a shared memory programming model, for example, OpenMP and Intel's Threading Building Blocks.
Since
for (int i = 3; i <= something / 2; i = i + 2)
{
...
}
can be rewritten into
for (int k = 1; k < (something + 2) / 4; ++k)
{
int i = 1 + 2 * k;
...
}
you can put
Parallel.For(1, (something + 2) / 4, k =>
{
int i = 1 + 2 * k;
...
});
The third parameter is a delegate
. So every iteration you could specify what your indexing variable shall do inside the delegate.
EDIT: Ok found a working solution:
As already suggested by Dmitry Bychenko you should still start from 0 and just add the startValue
as an offset
int something = 16;
int startValue = 3;
int stepSize = 2;
List<int> numbers = Enumerable.Range(0, 20).ToList();
Parallel.For(0, something / 2, i =>
{
int ind = (stepSize * i) + startValue ; Console.WriteLine(numbers[ind]);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With