Using a multi-core processor (-thread) for a FOR loop

I have a simple loop for:

for (int i = 1; i <= 8; i++) { DoSomething(i); } int nopt = 8; //number of processor threads 

I would like to do DoSomething(1) in processor thread 1,
DoSomething(2) in thread 2


DoSomething(8) in thread 8.

Is it possible? If so, how?

Thanks for answers.

+5
source share
1 answer

You can try Parallel.For :

  int nopt = 8; ParallelOptions po = new ParallelOptions() { MaxDegreeOfParallelism = nopt, }; // 9 is exclusive when you want i <= 8 Parallel.For(1, 9, po, i => DoSomething(i)); 

PLinq (Parallel Linq) is an alternative:

  Enumerable .Range(1, 8) .AsParallel() .WithDegreeOfParallelism(nopt) .ForAll(i => DoSomething(i)); 
+11
source

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


All Articles