我需要这一领域的挥发?这一、领域

2023-09-04 08:26:25 作者:记忆的回迁

我有一个线程旋转,直到被另一个线程改变一个int有一定的价值。

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; 
}

难道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?

推荐答案

是的,这是一个硬性要求。刚刚在时间编译器被允许存储m_cur在一个寄存器的值,而无需从存储器刷新它。事实上,86抖动呢,x64的抖动不会(至少我最后一次看着它)。

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).

在挥发性的关键字必须燮preSS这种优化。

The volatile keyword is required to suppress this optimization.

挥发性意味着什么安腾内核完全不同的,有内存模型弱的处理器。不幸的是,这就是把它做成MSDN库和C#语言规范。它是什么将意味着ARM内核上,还有待观察。

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.