4

是否有人知道一种无锁方式来执行逻辑上等同于 compare_and_swap_if_greater_than() 的操作?我们有 compare_and_swap(),它实际上是 compare_and_swap_if_equal()。我现在最好的方法是使用自旋互斥锁,但我认为巧妙地使用历史变量、循环和 compare_and_swap() 可能可以避免这种情况。

4

1 回答 1

1

这个怎么样:

public static void CompareAndSwapIfGreaterThan(ref int location, int newValue) {
  while(true) {
    var currentValue=Thread.VolatileRead(ref location);
    if(newValue<=currentValue
      || Interlocked.CompareExchange(ref location, newValue, currentValue)==currentValue) {
      return;
    }
  }
}
于 2011-09-20T03:34:19.830 回答