gpt4 book ai didi

c# - 如果用不同数量的线程并行调用,为什么会得到不同的总和?

转载 作者:行者123 更新时间:2023-12-03 13:23:29 25 4
gpt4 key购买 nike

这只是我提出的以下问题的延伸:

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

如果修改并行工作的任务数,则会得到不同的总和。

为什么会这样呢?

最佳答案

因为这条线:

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

考虑 threads = 3count = 10它不能涵盖您的所有列表。根据线程数,您在 takeskip中会得到不同的舍入,有时它们不能覆盖列表中的所有项。

您也许应该这样更改它:
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));
}

关于c# - 如果用不同数量的线程并行调用,为什么会得到不同的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62100278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com