I see following code in C# usage of InterLocked
:
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))
}
}
I understand that InterLocked.CompareExchange
will work atomically.
But, will line : currVal = this.myVal
will read the latest value of myVal
?
Should not we have volatile
for this variable or currVal = InterLocked.Read(ref this.myVal)
for that line?