0

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?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Ashish Negi
  • 5,193
  • 8
  • 51
  • 95
  • What is this actually doing? It looks nasty. [This](https://stackoverflow.com/q/1581718/14357) is relevant to parts of your question, but I'm sure there's a better way of expressing the intent of the code above that doesn't feel like it will spew in your face. – spender Apr 05 '18 at 17:52
  • Regarding to [Threading in C#](http://www.albahari.com/threading/part4.aspx#_Interlocked), all of Interlocked’s methods generate a full fence. So, you do not need to mark the field as `volatile` – Artavazd Balayan Apr 05 '18 at 18:50
  • @spender I just wrote that code on the fly. I wanted to focus on only line that i had problem with. Thanks for pointing me to right answer. If you don't mind, what is the problem you are seeing with this code. If you mean `classname` and `functionname` are bad, i just wanted to give a simple example. – Ashish Negi Apr 06 '18 at 16:29
  • @AshishNegi I wouldn't dare critique your code without fully understanding what its purpose is. What are you actually trying to do, and are you doing it concurrently? – spender Apr 06 '18 at 21:03

0 Answers0