我在InterLocked
的C#用法中看到以下代码:
class MyObj {
// some class code ..
int myVal
public void foo()
{
int currVal = 0, newVal = 0;
do
{
currVal = this.myVal; // I have the question here ?
newVal = this.newValue(currVal);
} while (currVal != InterLocked.CompareExchange(ref this.myVal, newVal, currVal))
}
}
我知道InterLocked.CompareExchange
会原子地运作。
但是,行:currVal = this.myVal
会读取myVal
的最新值吗?
我们不应该为此变量volatile
或该行的currVal = InterLocked.Read(ref this.myVal)
。 ?