【发布时间】:2012-04-25 00:20:20
【问题描述】:
我有一个线程旋转,直到另一个线程更改的 int 是某个值。
int cur = this.m_cur;
while (cur > this.Max)
{
// spin until cur is <= max
cur = this.m_cur;
}
是否需要将 this.m_cur 声明为 volatile 才能使其工作?由于编译器优化,这可能会永远旋转吗?
【问题讨论】:
-
将 int 设为属性并在 setter 方法中向线程发出信号(可能是 autoResetEvent)。绕过了问题,减少了 CPU 使用率,消除了不稳定的疑虑。
-
除了极少数情况外,这通常是个坏主意;你碰巧知道你希望旋转最多多少微秒吗?
-
CPU-looping while read 'cur' that iswritten by another thread will fail to detect cur out-of-limit if the polling thread is not running when the setter thread write an out-of-limit价值。如果它在过载的盒子上被抢占,它必须等待平均半个量子才能检测到超出范围的电流。如果 cur 在轮询器未运行时再次回到范围内,则根本不会检测到超出范围的情况。
-
@EricLippert 它只会在另一个线程的这两行代码之间旋转,所以它应该非常快。旋转的轮询线程也是一个低于正常的优先级。 if(Interlocked.Add(ref this.m_cur, x) > this.Max) this.m_cur = this.Max;
标签: c# .net multithreading volatile