我正在看p上的示例。斯蒂芬·克莱里(Stephen Cleary)书中的40
// Note: this is not the most efficient implementation.
// This is just an example of using a lock to protect shared state.
static int ParallelSum(IEnumerable<int> values)
{
object mutex = new object();
int result = 0;
Parallel.ForEach(source: values,
localInit: () => 0,
body: (item, state, localValue) => localValue + item,
localFinally: localValue =>
{
lock (mutex)
result += localValue;
});
return result;
}
我有点困惑为什么lock
需要它。因为如果我们要做的只是对int
s的集合求和,例如{1, 5, 6}
,那么我们就不必关心共享和result
以任何顺序递增。
(1 + 5) + 6 = 1 + (5 + 6) = (1 + 6) + 5 = ...
有人可以解释我的想法在哪里有缺陷吗?
我想我对方法的主体有点困惑
int result = 0;
Parallel.ForReach(values, (val) => { result += val; });
return result;
该语句result += localValue;
实际上result = result + localValue;
是在说您正在读取和更新不同线程共享的资源(变量)。这很容易导致竞争状况。lock
确保在任何给定的时间点通过单个线程访问该语句。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句