ParallelOptions with MaxDegreeOfParallelism and actual number of threads

Viewed 411

Hello I am doing "dynamic" multithreading with different values of MaxDegreeOfParallelism method but whenever I am trying to change value of MaxDegreeOfParallelism that's greater than 1 it's showing in console that program use more threads than I assigned.

public static string DoMultipleTasks(int threads, List<string> inputList)
{            
    ParallelOptions po = new ParallelOptions();          
    po.MaxDegreeOfParallelism = threads;
    Parallel.ForEach(inputList, po,  values =>
    {
        Console.WriteLine(" Name: {0}, Thread Id= {1}", values, Thread.CurrentThread.ManagedThreadId);
    });            
    return null;
}

Output:

enter image description here

1 Answers

MaxDegreeOfParallelism specifies how many threads (or rather, tasks) can run at the same time. It doesn't specify which threads that should be.

From the docs:

Gets or sets the maximum number of concurrent tasks enabled by this ParallelOptions instance.

During your execution of Parallel.ForEach you may run on many different threads (and therefore involve many different thread id's). That depends on the underlying thread scheduler.

You are, however, guaranteed that your block of code will at most have MaxDegreeOfParallelism executions at the same time.

While you basically have an example already, here is a slightly modified version of your code to show what I mean.

var dict = new ConcurrentDictionary<int, string>();
var po = new ParallelOptions { MaxDegreeOfParallelism = 3 };
int count = 0, maxval = 0;
Parallel.ForEach(Enumerable.Range(1, 10000000), po, (d) =>
{
    Interlocked.Increment(ref count);
    dict.AddOrUpdate(Thread.CurrentThread.ManagedThreadId, "", (id, old) => old);

    lock (dict)
    {
        maxval = Math.Max(maxval, count);
    }
    Interlocked.Decrement(ref count);
});

Console.WriteLine("Count: " + count);
Console.WriteLine("Max: " + maxval);
Console.WriteLine("Thread ids: " + String.Join(", ", dict.Select(d => d.Key)));

It should result in an output similar to this:

Count: 0
Max: 3
Thread ids: 1, 4, 5, 6, 7, 8, 9

No matter how many times you run this code, the max value should never go above 3. On the other hand, the thread ids will change often.

Related