Change loop for Parallel.For loop

I can change my cycle

for (int i = 0; i < something; i++) 

in

 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.

+5
source share
3 answers

As

 for (int i = 3; i <= something / 2; i = i + 2) { ... } 

can be rewritten in

 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; ... }); 
+7
source

Third parameter: delegate . Therefore, each iteration, you can specify what your indexing variable should do inside the delegate.

EDIT: Well-found working solution: As suggested by Dmitry Bychenko, you should still start at 0 and just add 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]); }); 
+3
source

Dmitry Bychenko answer this, but you can also implement your own ParallelFor with a custom step that will make your code a little more readable:

 static void ParallelFor(int start, int last, Func<int, int> step, Action<int> action) { var enumerable = StepEnumerable<int> .Create(start, step) .TakeWhile(x => x < last); Parallel.ForEach(enumerable, action); } 

Here is the implementation of StepEnumerable :

 public class StepEnumerator<T> : IEnumerator<T> { ... public StepEnumerable(T value, Func<T, T> manipulation) { mEnumerator = new StepEnumerator<T>(value, manipulation); } public static StepEnumerable<T> Create(T value, Func<T, T> manipulation) { return new StepEnumerable<T>(value, manipulation); } ... } public class StepEnumerator<T> : IEnumerator<T> { public bool MoveNext() { Current = mManipulation(Current); return true; } } 

Then, for example, if you run the following code:

 ParallelFor(3, 16, x => x + 2, Console.WriteLine); 

You will get the following output (on separate lines, of course):

5, 11, 7, 13, 9, 15

+1
source

Source: https://habr.com/ru/post/1260656/


All Articles