Platform SDK: DLLs, Processes, and Threads

InterlockedCompareExchange

The InterlockedCompareExchange function performs an atomic comparison of the specified values and exchanges the values, based on the outcome of the comparison. The function prevents more than one thread from using the same variable simultaneously.

If you are exchanging pointer values, this function has been superseded by the InterlockedCompareExchangePointer function.

LONG InterlockedCompareExchange( 
  LPLONG Destination,  // destination address
  LONG Exchange,       // exchange value
  LONG Comperand       // value to compare
);

Parameters

Destination
[in/out] Specifies the address of the destination value. The sign is ignored.
Exchange
[in] Specifies the exchange value. The sign is ignored.
Comperand
[in] Specifies the value to compare to Destination. The sign is ignored.

Return Values

The return value is the initial value of the destination.

Remarks

The functions InterlockedCompareExchange, InterlockedDecrement, InterlockedExchange, InterlockedExchangeAdd, and InterlockedIncrement provide a simple mechanism for synchronizing access to a variable that is shared by multiple threads. The threads of different processes can use this mechanism if the variable is in shared memory.

The InterlockedCompareExchange function performs an atomic comparison of the Destination value with the Comperand value. If the Destination value is equal to the Comperand value, the Exchange value is stored in the address specified by Destination. Otherwise, no operation is performed.

The variables for InterlockedCompareExchange must be aligned on a 32-bit boundary; otherwise, this function will fail on multiprocessor x86 systems and any non-x86 systems.

Requirements

  Windows NT/2000: Requires Windows NT 4.0 or later.
  Windows 95/98: Requires Windows 98.
  Header: Declared in Winbase.h; include Windows.h.
  Library: Use Kernel32.lib.

See Also

Synchronization Overview, Synchronization Functions, Interlocked Variable Access, InterlockedCompareExchangePointer, InterlockedDecrement, InterlockedExchange, InterlockedExchangeAdd, InterlockedIncrement