Interlocked.CompareExchange using GreaterThan or LessThan instead of equality

后端 未结 7 1320
别跟我提以往
别跟我提以往 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

    What do you think about this implementation:

    // this is a Interlocked.ExchangeIfGreaterThan implementation
    private static void ExchangeIfGreaterThan(ref long location, long value)
    {
        // read
        long current = Interlocked.Read(ref location);
        // compare
        while (current < value)
        {
            // set
            var previous = Interlocked.CompareExchange(ref location, value, current);
            // if another thread has set a greater value, we can break
            // or if previous value is current value, then no other thread has it changed in between
            if (previous == current || previous >= value) // note: most commmon case first
                break;
            // for all other cases, we need another run (read value, compare, set)
            current = Interlocked.Read(ref location);
        }
    }
    
    0 讨论(0)
提交回复
热议问题