Interlocked.CompareExchange using GreaterThan or LessThan instead of equality

后端 未结 7 1415
别跟我提以往
别跟我提以往 2020-12-24 07:23

The System.Threading.Interlocked object allows for Addition (subtraction) and comparison as an atomic operation. It seems that a CompareExchange that just does

7条回答
  •  感动是毒
    2020-12-24 07:52

    With these helper methods you can not only exchange value but also detect was it replaced or not.

    Usage looks like this:

    int currentMin = 10; // can be changed from other thread at any moment
    
    int potentialNewMin = 8;
    if (InterlockedExtension.AssignIfNewValueSmaller(ref currentMin, potentialNewMin))
    {
        Console.WriteLine("New minimum: " + potentialNewMin);
    }
    

    And here are methods:

    public static class InterlockedExtension
    {
        public static bool AssignIfNewValueSmaller(ref int target, int newValue)
        {
            int snapshot;
            bool stillLess;
            do
            {
                snapshot = target;
                stillLess = newValue < snapshot;
            } while (stillLess && Interlocked.CompareExchange(ref target, newValue, snapshot) != snapshot);
    
            return stillLess;
        }
    
        public static bool AssignIfNewValueBigger(ref int target, int newValue)
        {
            int snapshot;
            bool stillMore;
            do
            {
                snapshot = target;
                stillMore = newValue > snapshot;
            } while (stillMore && Interlocked.CompareExchange(ref target, newValue, snapshot) != snapshot);
    
            return stillMore;
        }
    }
    

提交回复
热议问题