以下是基于Interlocked.CompareExchange
的互锁方法的实现。
此代码是否建议在重复之前使用spinwait
旋转?
public static bool AddIfLessThan(ref int location,int value,int comparison)
{
int currentvalue;
do
{
currentvalue = location; // Read the current value
if (currentvalue >= comparison) return false; // If "less than comparison" is NOT satisfied,return false
}
// Set to currentvalue+value,iff still on currentvalue; reiterate if not assigned
while (Interlocked.CompareExchange(ref location,currentvalue + value,currentvalue) != currentvalue);
return true; // Assigned,so return true
}
我已经看到spinwait
在这种情况下使用,但是我的理论是应该没有必要。毕竟,该循环仅包含少量指令,并且总是有一个线程在进展。
假设有两个线程竞相执行此方法,并且第一个线程立即成功执行,而第二个线程最初不做任何更改,必须重申。没有其他竞争者,第二个线程是否有可能在第二次尝试中失败?
如果示例的第二个线程在第二次尝试上无法失败,那么使用spinwait
会得到什么?如果不太可能发生一百个线程争分夺秒地执行该方法的情况,可以缩短几个周期?