Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MaxDegreeOfParallelism = 2 shows 3 threads

When I run the following code:

public static double SumRootN(int root)
{
    double result = 0;
    for (int i = 1; i < 10000000; i++)
    {
        result += Math.Exp(Math.Log(i) / root);
    }
    return result;
}

static void Main()
{
    ParallelOptions options = new ParallelOptions();
    options.MaxDegreeOfParallelism = 2; // -1 is for unlimited. 1 is for sequential. 

    try
    {
        Parallel.For(
                0,
                9,
                options,
                (i) =>
        {
            var result = SumRootN(i);
            Console.WriteLine("Thread={0}, root {0} : {1} ",
                Thread.CurrentThread.ManagedThreadId, i, result);
        });
    }
    catch (AggregateException e)
    {
        Console.WriteLine(
            "Parallel.For has thrown the following (unexpected) exception:\n{0}", e);
    }
}

I see that the output is:

Screenshot

There are 3 thread Ids here, but I have specified that the MaxDegreeOFParallelism is only 2. So why is there 3 threads doing the work instead of 2?

like image 748
Harry Boy Avatar asked Feb 25 '26 03:02

Harry Boy


1 Answers

Quote from http://msdn.microsoft.com/en-us/library/system.threading.tasks.paralleloptions.maxdegreeofparallelism(v=vs.110).aspx

By default, For and ForEach will utilize however many threads the underlying scheduler provides, so changing MaxDegreeOfParallelism from the default only limits how many concurrent tasks will be used.

Translation: only 2 threads will be running at any given moment, but more (or even less) than 2 may be used out of the thread pool. You can test this with another writeline at the start of the task, you'll see that no 3 threads will enter concurrently.

like image 101
fejesjoco Avatar answered Feb 27 '26 18:02

fejesjoco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!