我编写了NasdaqIndex计算的简单示例。为了简单起见,我宣布它为int,这只是10股票价格的总和。
class NasdaqIndex {
private int[] stockValue = new int[10]; // for simplicity let's assume they are already initialized
// just sum from 1 to 10 of stockValue
private int nasdaqIndexValue; // for simplicity let's assume that already initialized
public void StockValueUpdated(int stockValueIndex, int newValue) {
int diff = newValue - stockValue[stockValueIndex];
stockValue[stockValueIndex] = newValue;
nasdaqIndexValue += diff; // THIS NEED TO BE SYNCHRONIZED!
}
}但是在现实生活中,StockValueUpdated可能(而且将)被不同的线程调用为不同的stockValueIndex (对于相同的stockValueIndex,它不会被称为并行)。
所以我只需要同步一行代码nasdaqIndexValue += diff;
例如,如果一个线程执行nasdaqIndexValue += 10;,另一个线程执行nasdaqIndexValue += 3;,我需要确保添加的正是13。在这种情况下,我需要同步吗?如果是这样的话,如何使用lock-free代码来实现呢?
UPD oooops我刚刚意识到,每次使用双打时,我都会向nasdaqIndex引入小的“增量”。因此,我要么使用十进制,要么我必须“完全重新计算”nasdaqIndex有时,否则它将不等于股票之和一段时间。
发布于 2012-07-05 13:53:10
使用Interlocked类型将该操作作为原子操作:
Interlocked.Add(ref nasdaqIndexValue, diff);发布于 2012-07-05 13:56:36
使用volatile关键字。
易失性修饰符通常用于由多个线程访问的字段,而不使用lock语句序列化访问。
private volatile int nasdaqIndexValue; // for simplicity let's assume that already initializedhttps://stackoverflow.com/questions/11345634
复制相似问题