我在单线程环境中有以下过程:
int[] ages = { 40, 30, 18, 23, 60, 24 };
for (int i = 0; i < ages.Length; i++)
{
if (ages[i] < 21) ages[i] = 0;
}
作为示例,但现在我想在多线程环境中执行此过程。 是否有一个Concurrent集合在多线程环境中模拟一个数组?
答案 0 :(得分:4)
您可以尝试使用 Parallel Linq ( PLinq )并让.Net 实现最终结果作为数组;在你的情况下:
int[] ages = { 40, 30, 18, 23, 60, 24 };
ages = ages
.AsParallel()
.Select(age => age < 21 ? 0 : age)
.ToArray();
PLinq 的优点是.Net负责内部集合选择,锁定等。如果你想要,比如说,找到一个平行的年龄并行,你所要做的就是稍微编辑查询:
var averageAge = ages
.AsParallel()
.Average();
答案 1 :(得分:2)
最近的解决方案是使用索引作为键来使用ConcurrentDictionary。在这种情况下,哈希函数非常好:
var dict = new ConcurrentDictionary<int, int>(Enumerable.Range(0, ages.Length).ToDictionary(i => i, i => ages[i]));
Parallel.For(0, dict.Count,
i =>
{
int value;
if (dict.TryGetValue(i, out value) && value < 21)
dict.TryUpdate(i, value, 0);
});
请注意这个特定示例根本不需要使用ConcurrentDictionary的事实,因为每次迭代之间没有依赖关系。
Parallel.For(0, ages.Length,
i =>
{
if (ages[i] < 21) ages[i] = 0;
});
此代码非常适合您的示例。下次使用更复杂的东西,比如数组元素的总和。
希望这有帮助!