【发布时间】:2012-05-26 23:14:49
【问题描述】:
在我的 C# 程序中,我有方法代码:
Object model;
int score;
for()
{
int tempScore=0;
Object tempModel=getModel();
//some interesting stuff modifying value of tempScore
if(tempScore>score)
{
score=tempScore;
model=tempModel;
}
}
我想使用 Parallel 进行正常的 insted,但我担心我会遇到一些同步问题。我知道我可以使用 lock(model),但是对于简单类型分数我能做些什么呢? model 和 score 是方法局部变量,因此它们在线程之间共享。
【问题讨论】:
-
sn-p 不够清晰。考虑线程局部变量。基本的操作方法文章在这里:msdn.microsoft.com/en-us/library/dd460703.aspx
-
我们需要知道哪些变量是线程间共享的。我们可以猜测
score是共享的。您可以在 map/reduce 算法中使用线程本地分数。或者您可以使用联锁操作。或锁定。
标签: c# .net for-loop parallel-processing