parallel within parallel code

試著忘記壹切 提交于 2021-02-10 16:25:19

问题


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)


回答1:


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);
        });
    });
    



回答2:


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
});   


来源:https://stackoverflow.com/questions/26707177/parallel-within-parallel-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!