Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to run 500 different operations in multiple threads at the same time?

I have, let's say, a list with 500 objects. For each object, I'm calling a function calculating it's cost. So each of the 500 calls is independent from the others. The overall takes around 30 seconds. Wouldn't it be possible to run all the 500 tasks at the same time as they don't rely on each other ? I know nothing about multi-threading therefore I don't know if it could be a solution.

like image 926
TD Lemon Avatar asked Dec 09 '25 13:12

TD Lemon


2 Answers

You can easily parallelize the work using the Parallel.ForEach Method:

Parallel.ForEach(items, item =>
{
    item.CalculateCost();
});
like image 72
dtb Avatar answered Dec 12 '25 02:12

dtb


Running a single threaded process will only use one-core of your machine (this does allow other cores to run operating system and other application processes).

Your process sounds liek a good contender for multi-threaded processing, however you don't need a new thread for every process - this will create overhead in creating the threads, and also you won't have enough cores to run them all individually, so they will be fighting for CPU resources.

Using Parallel.For in .Net4.0 will cleverly use as many threads as it can.

like image 28
cjk Avatar answered Dec 12 '25 03:12

cjk



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!