Atomic exchange value as a result of comparison

I have a very simple operation that should be performed atomically:

if (a > b)
  b = a

where a and b are ints

EDIT: and a is local.

Is there a quick way to do this in C #? I would like to avoid blocking manually if possible. I looked at Interlocked.CompareExchange, but as I understand it, these are just tests for equality.

Thank!

+5
source share
3 answers

The canonical method is to use interchangeable exchange exchange in a cycle:

int oldvalue, newvalue ;
do {
  oldvalue = b ; // you'll want to force this to be a volatile read somehow
  if( a > oldvalue )
    newvalue = a ;
  else
    break ;
} while( interlocked replace oldvalue with newvalue in b does NOT succeed );

(Pseudocode, because I'm not trying to find the right way to make a blocked exchange in C #).

, , .

: , a , , . a, b , . ( ).

+7

. , #. .

public static T InterlockedOperation<T>(ref T location, T operand)
{
  T initial, computed;
  do
  {
    initial = location;
    computed = op(initial, operand); // where op is replaced with a specific implementation
  } 
  while (Interlocked.CompareExchange(ref location, computed, initial) != initial);
  return computed;
}

InterlockedGreaterThanExchange, .

public static int InterlockedGreaterThanExchange(ref int location, int value)
{
  int initial, computed;
  do
  {
    initial = location;
    computed = value > initial ? value : initial;
  } 
  while (Interlocked.CompareExchange(ref location, computed, initial) != initial);
  return computed;
}
+3

, . # Interlocked, CompareExchenge() Exchange(), (32 32- 64- 64- ).

, a = b - - . , + ... /, ?;)

: , "a" - ... uhhhggg ... , , - "",

, :

  • ,
  • - ( , , a , a, b
object lockObject = new object();
int a = 10;
int b = 5;

lock (lockObject)
{
   if (a > b)
   {
      b = a
   }
}
-1

All Articles