Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Multi-core (-thread) processor for FOR loop

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.

like image 677
Monna L Avatar asked Dec 05 '16 10:12

Monna L


People also ask

Can threads run on multiple processors?

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.

Can we run a multi threaded program on multiple processors in parallel?

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.

Does multithreading use multiple cores?

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.

How many threads can parallel run in C#?

So, you can have a total maximum of 20 threads executing in parallel, one thread per CPU/core.


1 Answers

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));
like image 62
Dmitry Bychenko Avatar answered Nov 01 '22 12:11

Dmitry Bychenko