Why I am getting a different sum if invoked with different number of threads in parallel?

拜拜、爱过 提交于 2020-06-28 03:57:36

问题


This is just an extension of the following question I asked:

Why can't I reach 100% CPU utilization with my parallel tasks code?

 private static int SumParallel()
        {
            var intList = Enumerable.Range(1, 1000_000_000);
            int count = intList.Count();
            int threads = 6;
            List<Task<int>> l = new List<Task<int>>(threads);
            for(int i = 1; i <= threads; i++)
            {
                int skip = ((i - 1) * count) / threads;
                int take = count / threads;
                l.Add(GetSum(intList, skip, take));
            }
            Task.WaitAll(l.ToArray());
            return l.Sum(t => t.Result);
        }

private static Task<int> GetSum(IEnumerable<int> list, int skip, int take)
        {
            return Task.Run(() =>
             {
                 int temp = 0;
                 foreach(int n in list.Skip(skip).Take(take))
                 {
                     if (n % 2 == 0)
                         temp -= n;
                     else
                     {
                         temp += n;
                     }
                 }

                 Console.WriteLine(temp + " " + Task.CurrentId);
                 return temp;
             });
        }

If I modify the number of tasks working in parallel, I get a different sum.

Why is this so?


回答1:


It's because of this line:

int skip = ((i - 1) * count) / threads;
int take = count / threads;

consider threads = 3 and count = 10 It can't cover all of your list. Based on thread count you get different roundings in take and skip and sometimes they can't cover all items in the list.

You maybe should change it this way:

for(int i = 1; i <= threads; i++)
{
    int skip = ((i - 1) * count) / threads;
    int take = count / threads;

    if(i == threads)
        take = threads - skip;

    l.Add(GetSum(intList, skip, take));
}


来源:https://stackoverflow.com/questions/62100278/why-i-am-getting-a-different-sum-if-invoked-with-different-number-of-threads-in

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