In Delphi, the InterlockedCompareExchange function is used to perform an atomic compare-and-swap operation on a 32-bit value. This function compares a given value to a specified target value, and if they are equal, it exchanges the target value with a new value. The function returns the original value of the target.
Here is an example of how to use InterlockedCompareExchange in Delphi
1 2 3 4 5 6 7 |
var OriginalValue: Integer; TargetValue: Integer; NewValue: Integer; begin OriginalValue := InterlockedCompareExchange(TargetValue, NewValue, TargetValue); end; |
In this example, OriginalValue will contain the original value of TargetValue before the exchange. If TargetValue and the specified value are equal, TargetValue will be set to NewValue. If they are not equal, no exchange will occur and TargetValue will retain its original value.
InterlockedCompareExchange is useful for implementing thread-safe synchronization in multi-threaded applications, as it allows multiple threads to access and update a shared resource without the risk of race conditions.
Leave a Reply