35

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
5
  • Is that really the example presented? Because it's really invalid at the moment. Could you show where that's presented? Commented Apr 10, 2013 at 16:27
  • Yeah. Well, here I only presented the relevant fragment. The whole example is here: msdn.microsoft.com/en-us/library/dd460713.aspx Commented Apr 10, 2013 at 16:34
  • You presented a fragment which is syntactically incorrect, by sticking "System.Threading.Tasks.TaskCreationOptions" in the middle of the argument list for no reason. Commented Apr 10, 2013 at 16:48
  • Oops! Sorry, I was blind to what you were saying. Fixed. Commented Apr 10, 2013 at 16:51
  • possible duplicate of Limit the number of parallel threads in C# Commented Oct 16, 2014 at 13:47

3 Answers 3

57

You need to specify a ParallelOptions value with a MaxDegreeOfParallelism:

For example:

Parallel.For(0, 10, new ParallelOptions { MaxDegreeOfParallelism = 4 }, count =>
{
    Console.WriteLine(count);
});
Sign up to request clarification or add additional context in comments.

for Parallel for each use : Parallel.ForEach(lines,new ParallelOptions { MaxDegreeOfParallelism = 4 }, line => { Console.WriteLine(line); });
6

Use MaxDegreeOfParalelism property for running the loop

Parallel.For(0, 1000, new ParallelOptions { MaxDegreeOfParallelism = 2 }, ...);

Comments

5

I'd suggest you take a look at the ParallelOption.MaxDegreesofParellelism and pass it into the For method

Comments

Your Answer

Draft saved
Draft discarded

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.