Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 512
noctonura Avatar asked Apr 25 '12 00:04

noctonura


1 Answers

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.

like image 69
Hans Passant Avatar answered Oct 06 '22 20:10

Hans Passant