InterlockedCompareExchange

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

PVOID InterlockedCompareExchange( 
  PVOID *Destination,  // pointer to the destination pointer
  PVOID Exchange,      // the exchange value
  PVOID Comperand      // the value to compare
);
 

Parameters

Destination
Specifies the address of the destination value. This is a 32-bit value. The sign is ignored.
Exchange
Specifies the exchange value. This is a 32-bit value. The sign is ignored.
Comperand
Specifies the value to compare to Destination. This is a 32-bit value. 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.

QuickInfo

  Windows NT: Requires version 4.0 or later.
  Windows: Requires Windows 98 or later.
  Windows CE: Unsupported.
  Header: Declared in winbase.h.
  Import Library: Use kernel32.lib.

See Also

Synchronization Overview, Synchronization Functions, InterlockedDecrement, InterlockedExchange, InterlockedExchangeAdd, InterlockedIncrement