加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为什么需要锁?

发布时间:2020-12-15 19:53:48 所属栏目:百科 来源:网络整理
导读:我正在看一个关于p的例子.斯蒂芬克莱里的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(IEnumerableint values){ object mutex
我正在看一个关于p的例子.斯蒂芬克莱里的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;
}

我有点困惑为什么需要锁.因为如果我们所做的只是汇总一组整数,比如说{1,5,6},那么我们就不需要关心以任何顺序递增的共享和结果.

(1 + 5) + 6 = 1 + (5 + 6) = (1 + 6) + 5 = ...

有人能解释我的思想在哪里有缺陷吗?

我想我的身体方法有点困惑不能简单

int result = 0;
Parallel.ForReach(values,(val) => { result += val; }); 
return result;

解决方法

语句结果= localValue;真的是说结果=结果localValue;您正在读取和更新由不同线程共享的资源(变量).这很容易导致竞争条件. lockmakes确保在任何给定时刻该语句由单个线程访问.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读