4

Is anybody aware of a lockless way to perform what is logically equivalent to a compare_and_swap_if_greater_than()? We have compare_and_swap(), which is really compare_and_swap_if_equal(). The best I have right now is to use a spin mutex, but I think withclever uses of history variables, loops, and compare_and_swap() it may be possible to avoid this.

tgoodhart
  • 3,111
  • 26
  • 37

1 Answers1

1

How about this:

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;
    }
  }
}
Corey Kosak
  • 2,615
  • 17
  • 13
  • I'm not sure this is correct. I think minimally you need a loop around the latter condition in the OR for the case where != currentValue. I could certainly be wrong though. – tgoodhart Sep 20 '11 at 03:51
  • @tgoodhart: I think the outer loop takes care of that case. This is a pretty standard formulation for updating a value atomically using compare&swap... Read old value; compute new value; conditionally store new value; and try again if someone beat you to it. I believe this works. – Nemo Sep 20 '11 at 04:26