Search code examples
c#thread-safetyinterlocked

Interlocked.CompareExchange single-threaded equivalent code


I don't know why, but I can't quite seem to wrap my head around what's going on in Interlocked.CompareExchange(ref int a, int b, int c).

Could someone show me what it would be doing, if it were just naively implemented in a single-threaded environment?

i.e. what code is it replacing with a "do that ... but as an atomic, thread-safe operation"?


Solution

  • Here's my understanding of the code (in single-threaded land):

    static int CompareExchange(ref int location1, int value, int comparand)
    {
        var valueToReturn = location1;
        if (location1 == comparand)
        {
            location1 = value;
        }
    
        return valueToReturn;
    }
    

    Taken from the docs here: https://learn.microsoft.com/en-us/dotnet/api/system.threading.interlocked.compareexchange

    Parameters

    • location1 (Int32)
      The destination, whose value is compared with comparand and possibly replaced.
    • value (Int32)
      The value that replaces the destination value if the comparison results in equality.
    • comparand (Int32)
      The value that is compared to the value at location1.
    • Returns (Int32)
      The original value in location1.

    Remarks

    If comparand and the value in location1 are equal, then value is stored in location1. Otherwise, no operation is performed. The compare and exchange operations are performed as an atomic operation. The return value of CompareExchange is the original value in location1, whether or not the exchange takes place.