Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change for loop to Parallel.For loop

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.

like image 208
Monna L Avatar asked Dec 01 '16 15:12

Monna L


People also ask

Can FOR loops be parallel?

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.

How does a parallel loop work?

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.


2 Answers

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; 
    ... 
});
like image 50
Dmitry Bychenko Avatar answered Sep 30 '22 05:09

Dmitry Bychenko


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]);
});
like image 21
Mong Zhu Avatar answered Sep 30 '22 06:09

Mong Zhu