InterlockedCompareExchange function (winnt.h)
Performs an atomic compare-and-exchange operation on the specified values. The function compares two specified 32-bit values and exchanges with another 32-bit value based on the outcome of the comparison.
If you are exchanging pointer values, this function has been superseded by the InterlockedCompareExchangePointer function.
To operate on 64-bit values, use the InterlockedCompareExchange64 function.
Syntax
LONG InterlockedCompareExchange(
[in, out] LONG volatile *Destination,
[in] LONG ExChange,
[in] LONG Comperand
);
Parameters
[in, out] Destination
A pointer to the destination value.
[in] ExChange
The exchange value.
[in] Comperand
The value to compare to Destination.
Return value
The function returns the initial value of the Destination parameter.
Remarks
The function compares the Destination value with the Comparand value. If the Destination value is equal to the Comparand value, the Exchange value is stored in the address specified by Destination. Otherwise, no operation is performed.
The parameters for this function must be aligned on a 32-bit boundary; otherwise, the function will behave unpredictably on multiprocessor x86 systems and any non-x86 systems. malloc, calloc, HeapAlloc, and HeapReAlloc provide sufficiently aligned memory.
The interlocked functions provide a simple mechanism for synchronizing access to a variable that is shared by multiple threads. This function is atomic with respect to calls to other interlocked functions.
This function is implemented using a compiler intrinsic where possible. For more information, see the WinBase.h header file and _InterlockedCompareExchange.
This function generates a full memory barrier (or fence) to ensure that memory operations are completed in order.
Itanium-based systems: For performance-critical applications, use InterlockedCompareExchangeAcquire or InterlockedCompareExchangeRelease instead.
Requirements
Requirement | Value |
---|---|
Minimum supported client | Windows XP [desktop apps | UWP apps] |
Minimum supported server | Windows Server 2003 [desktop apps | UWP apps] |
Target Platform | Windows |
Header | winnt.h (include Windows.h) |
Library | Kernel32.lib |
DLL | Kernel32.dll |
See also
InterlockedCompare64Exchange128
InterlockedCompareExchange16Acquire
InterlockedCompareExchange16NoFence
InterlockedCompareExchange16Release
InterlockedCompareExchangeAcquire
InterlockedCompareExchangeAcquire64
InterlockedCompareExchangeNoFence
InterlockedCompareExchangeNoFence64
InterlockedCompareExchangePointer
InterlockedCompareExchangePointerAcquire
InterlockedCompareExchangePointerNoFence
InterlockedCompareExchangePointerRelease
InterlockedCompareExchangeRelease