gpt4 book ai didi

c# - Parallel.ForEach 同时保留顺序

转载 作者:太空狗 更新时间:2023-10-29 20:10:56 25 4
gpt4 key购买 nike

我有一个 List<byte[]>我喜欢反序列化每个 byte[]进入福。 List 是有序的,我喜欢编写一个并行循环,其中生成的 List<Foo>以与原始 byte[] 相同的顺序包含所有 Foo .该列表非常大,使并行操作值得。有没有内置的方法来完成这个?

如果没有,有什么想法可以通过同步运行来实现加速吗?

谢谢

最佳答案

根据您提供的信息,我了解到您想要一个大小等于输入字节数组的 Foo 输出数组?这样对吗?

如果是这样,是的,操作很简单。不要为锁定或同步构造而烦恼,它们会侵 eclipse 并行化为您提供的所有速度。

相反,如果您遵守这个简单的规则,任何算法都可以在没有锁定或同步的情况下并行化:

For each input element X[i] processed, you may read from any input element X[j], but only write to output element Y[i]

enter image description here

查找分散/聚集,这种类型的操作称为聚集,因为只写入一个输出元素。

如果您可以使用上述原则,那么您希望预先创建输出数组 Foo[],并在输入数组上使用 Parallel.For 而不是 ForEach。

例如

        List<byte[]> inputArray = new List<byte[]>();
int[] outputArray = new int[inputArray.Count];

var waitHandle = new ManualResetEvent(false);
int counter = 0;

Parallel.For(0, inputArray.Count, index =>
{
// Pass index to for loop, do long running operation
// on input items
// writing to only a single output item
outputArray[index] = DoOperation(inputArray[index]);

if(Interlocked.Increment(ref counter) == inputArray.Count -1)
{
waitHandle.Set();
}
});

waitHandler.WaitOne();

// Optional conversion back to list if you wanted this
var outputList = outputArray.ToList();

关于c# - Parallel.ForEach 同时保留顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11115049/

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