0
LONG __cdecl InterlockedCompareExchange(
  __inout  LONG volatile *Destination,
  __in     LONG Exchange,
  __in     LONG Comparand
);

Return value
The function returns the initial value of the Destination parameter.

Just curious.
Why does InterlockedCompareExchange return initial value? Is there a reason that they designed so?

Benjamin
  • 10,085
  • 19
  • 80
  • 130

2 Answers2

7

Because this gives you the most information. If you only know the changed value and it happens to be equal to Exchange, the inital value could be Exchange or it could be Comparand.

Henrik
  • 23,186
  • 6
  • 42
  • 92
2

Here's a good example from MSDN:

http://msdn.microsoft.com/en-us/library/windows/desktop/ms683560%28v=vs.85%29.aspx

    for(;;)
    {
        // calculate the function
        new_value = Random(old_value);

        // set the new value if the current value is still the expected one
        cur_value = InterlockedCompareExchange(seed, new_value, old_value);

        // we found the expected value: the exchange happened
        if(cur_value == old_value)
            break;

        // recalculate the function on the unexpected value
        old_value = cur_value;
    }

Do you see why it's important to be able to retain the initial value?

paulsm4
  • 114,292
  • 17
  • 138
  • 190