Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure a maximum number of threads in a Parallel.For

This is the example microsoft presents for the parallel for, and I'd like to know how configure a maximum number of threads for this code.

     // A basic matrix multiplication.      // Parallelize the outer loop to partition the source array by rows.      System.Threading.Tasks.Parallel.For(0, matARows, i =>      {         for (int j = 0; j < matBCols; j++)         {            // Use a temporary to improve parallel performance.            double temp = 0;            for (int k = 0; k < matACols; k++)            {               temp += matA[i, k] * matB[k, j];            }            result[i, j] = temp;         }      }); // Parallel.For 
like image 416
Alex. S. Avatar asked Apr 10 '13 16:04

Alex. S.


People also ask

How many threads will parallel ForEach use?

It could start 1000 threads for some degenerate 'DoSomething'.

What is the maximum number of threads in C#?

32767 in Framework 4.0 (64-bit environment)

What is Max degree of parallelism in C#?

Degree of parallelism is the maximum number of concurrently executing tasks that will be used to process the query. var result = Tabel.


2 Answers

You need to specify a ParallelOptions value with a MaxDegreeOfParallelism:

For example:

Parallel.For(0, 10, new ParallelOptions { MaxDegreeOfParallelism = 4 }, count => {     Console.WriteLine(count); }); 
like image 89
Jon Skeet Avatar answered Sep 19 '22 20:09

Jon Skeet


Use MaxDegreeOfParalelism property for running the loop

Parallel.For(0, 1000, new ParallelOptions { MaxDegreeOfParallelism = 2 }, ...); 
like image 41
Sasha Avatar answered Sep 22 '22 20:09

Sasha