N.T.C
N.T.C

Reputation: 658

parallel within parallel code

Once I have divided the tasks to 4 independent tasks and make them run in parallel. Is it possible to further make each task run in parallel ? (says, each task, there are lots of for each loop - that could be implemented as parallel code)

Upvotes: 1

Views: 640

Answers (2)

sribin
sribin

Reputation: 1736

Maybe you should reconsider your algorithm and keep only one Parallel.For(). The reason is described at this link: http://www.albahari.com/threading/part5.aspx in paragraph "Outer versus inner loops":

"Parallel.For and Parallel.ForEach usually work best on outer rather than inner loops. This is because with the former, you’re offering larger chunks of work to parallelize, diluting the management overhead. Parallelizing both inner and outer loops is usually unnecessary. In the following example, we’d typically need more than 100 cores to benefit from the inner parallelization":

Parallel.For (0, 100, i =>
{
    Parallel.For (0, 50, j => Foo (i, j));   // Sequential would be better
});   

Upvotes: 1

Ramie
Ramie

Reputation: 1201

You definitely could, but it doesn't guarantee thread safety.

You have to take into account multiple factors though

  • What's the size of your iterations (The more, the better)
  • How many concurrent threads can your CPU handle
  • The amount of cores in your processor

    Parallel.For(0, length1, i =>
    {
        Parallel.For(0, length2, j =>
        {           
            Console.WriteLine(i * j);
        });
    });
    

Upvotes: 0

Related Questions