0

What is the correct way to distribute operations to cores. Where I have four cores. I tried these codes. I don’t know if there is a better way. I hope for help

Parallel.For(0, 10,new ParallelOptions {MaxDegreeOfParallelism=10 } ,i =>
{
        //send to check if open port on any ip
});

Or alternatively:

Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++)
{
    threads[i] = new Thread(() => 
    {
        //send to check if open port on any ip
    });
}

Or alternatively:

Task[] tasks= new Task[10];
for (int i = 0; i < 10; i++)
{
    tasks[i] = new Task(() => 
    {
        //send to check if open port on any ip
    });
}
Brendan Green
  • 11,676
  • 5
  • 44
  • 76
  • So you have 4 cores and 10 operations, and you want to distribute the 10 operations to the 4 cores. The critical question is, are these operations [CPU-bound or I/O-bound](https://stackoverflow.com/questions/868568/what-do-the-terms-cpu-bound-and-i-o-bound-mean)? Because if they are I/O-bound (for example web requests), it doesn't really matter how many cores you have. You could have 1 core or 64 cores, and it would be absolutely the same. The number of cores is important if the operations are CPU-bound, for example if you have a huge number of calculations to perform. – Theodor Zoulias Apr 16 '20 at 16:05

1 Answers1

0

Parallel.For is generally the best one to go for.

The thing to remember is that you don't (generally) know how many cores you have on your target machine (unless you're writing for one very specific target). Thus any guesses at the degree of parallelization are dubious. Even if you know how many cores you have, you don't know how busy they are with other things.

The runtime system knows all these things and is better able to optimize than you as a programmer.

Thus, even with Parallel.For, there's not usually any need to specify a degree of parallelization.

Using Threads directly is usually a bad idea. If you ask for a Thread, you'll get one, even if the OS is running short of them, and that can slow things down.

If you use a Task the system may hold off giving you an actual thread if it is short of them. So using Tasks does leave the system to do some of the optimization, but Parallel.For is still easier.

Jasper Kent
  • 3,546
  • 15
  • 21