c# - 并行地。对于股票值(value)大于一个

标签 c# parallel-processing

问题来了

long sum = 0;
Parallel.For(1, 10000, y => { sum1 += y;} );

解决方案是..

Parallel.For<int>(0, result.Count, () => 0, (i, loop, subtotal) =>
{
    subtotal += result[i];
    return subtotal;
},
(x) => Interlocked.Add(ref sum, x)
);

如果这段代码中有两个参数。例如

long sum1 = 0; long sum2 = 0;
Parallel.For(1, 10000, y => { sum1 += y; sum2=sum1*y; } );

我们要做什么?我猜必须使用数组!

int[] s=new int[2];
Parallel.For<int[]>(0, result.Count, () => s, (i, loop, subtotal) =>
{
    subtotal[0] += result[i];
    subtotal[1] -= result[i];
    return subtotal;
},
(x) => Interlocked.Add(ref sum1, x[0])
//but how about sum2 i tried several way but it doesn't work. 
//for example like that
//(x[0])=> Interlocked.Add (ref sum1, x[0])
//(x[1])=> Interlocked.Add (ref sum2, x[1]));

);

最佳答案

我不确定我能否解决您的问题,因为我真的不知道它是什么。但是 Parallel.For 不容易支持这样的累加器是有充分理由的:因为尝试并行化具有副作用的简单操作是荒谬的。

Parallel.For 用于并行化相对昂贵的操作,这些操作没有相互依赖的副作用。常规的 for 循环(或 Accumulate)是正确的做法。

关于c# - 并行地。对于股票值(value)大于一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2907048/

相关文章:

c# - 与多个从站通信(基于 Modbus 协议(protocol))

r - R中并行计算的stdout和stderr

opencv - 使用 TBB 并行化 OpenCV 代码

c# - 是否有在后台线程上初始化对象的通用模式?

python - 给定 N 个生成器,是否可以创建一个在并行进程中运行它们并生成这些生成器的 zip 的生成器?

c# - Windows服务启动时如何运行任务?

c# - 如何使用 roslyn 获取项目的默认命名空间?

c - 您是否需要分配内存才能在 CUDA 中对数组进行操作?

c# - Visual Studio 2015 中的 ASP.NET MVC 项目中的引用似乎已损坏

c# - Twilio MessageResource.Read 日期是包含日期还是排除日期?