Search code examples
c#.netmultithreadingvolatile

Do I need this field to be volatile?


I have a thread that spins until an int changed by another thread is a certain value.

int cur = this.m_cur;
while (cur > this.Max)
{
    // spin until cur is <= max
    cur = this.m_cur; 
}

Does this.m_cur need to be declared volatile for this to work? Is it possible that this will spin forever due to compiler optimization?


Solution

  • Yes, that's a hard requirement. The just-in-time compiler is allowed to store the value of m_cur in a processor register without refreshing it from memory. The x86 jitter in fact does, the x64 jitter doesn't (at least the last time I looked at it).

    The volatile keyword is required to suppress this optimization.

    Volatile means something entirely different on Itanium cores, a processor with a weak memory model. Unfortunately that's what made it into the MSDN library and C# Language Specification. What it is going to to mean on an ARM core remains to be seen.