How to set the minimum value in .Net without using blocking?

I have several threads accessing variables. I know how to write spinlocks and use Threading.Interlocked methods to increase, etc. Of the variables.

However, I want to fulfill the equivalent:

a = Math.Min(a, b)
or
a = a | 10

... but without using a critical section. Is it possible? I know that the second line is possible in assembler, but there is no Interlocked.Or method.

+3
source share
2 answers

Here is a generic pattern to simulate a lock operation.

public static T InterlockedOperation<T>(ref T location, T value)
{
  T initial, computed;
  do
  {
    initial = location;
    computed = op(initial, value); // initial | value
  } 
  while (Interlocked.CompareExchange(ref location, computed, initial) != initial);
  return computed;
}

min - . , . , . , . volatile Thread.MemoryBarrier .

: , min a. , , computed = initial | value do computed = initial < value ? initial : value. .

+2

, , - ? (, , , .)

int original;    // assuming here that a is an int
do
{
    original = a;
} while (Interlocked.CompareExchange(ref a, original | 10, original) != original)
+2

All Articles