I have a simple loop for:
for (int i = 1; i <= 8; i++)
{
DoSomething(i);
}
int nopt = 8; //number of processor threads
I would like to do DoSomething(1)
in processor thread 1,DoSomething(2)
in thread 2
...DoSomething(8)
in thread 8.
Is it possible? If yes than how?
Thanks for answers.
Differences Between Cores And Threads Cores use content switching but threads use multiple processors for executing different processes. Cores require only a single unit of processing; threads require multiple processing units for task execution.
On a system with more than one processor or CPU cores (as is common with modern processors), multiple processes or threads can be executed in parallel. On a single core though, it is not possible to have processes or threads truly executing at the same time.
Multithreading is a form of parallelization or dividing up work for simultaneous processing. Instead of giving a large workload to a single core, threaded programs split the work into multiple software threads. These threads are processed in parallel by different CPU cores to save time.
So, you can have a total maximum of 20 threads executing in parallel, one thread per CPU/core.
You can try Parallel.For
:
int nopt = 8;
ParallelOptions po = new ParallelOptions() {
MaxDegreeOfParallelism = nopt,
};
// 9 is exclusive when you want i <= 8
Parallel.For(1, 9, po, i => DoSomething(i));
PLinq (Parallel Linq) is an alternative:
Enumerable
.Range(1, 8)
.AsParallel()
.WithDegreeOfParallelism(nopt)
.ForAll(i => DoSomething(i));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With