<p>I came across the function <a href="http://msdn.microsoft.com/en-us/library/ms683590(VS.85).aspx" rel="noreferrer" title="MSDN Link">InterlockedExchange</a> and was wondering when I should use this function. In my opinion, setting a 32 Bit value on an x86 processor should always be atomic? <br/>
In the case where I want to use the function, the new value does not depend on the old value (it is not an increment operation).
Could you provide an example where this method is mandatory (I'm not looking for InterlockedCompareExchange)</p>

```
InterlockedExchange
```
is both a write
and
a read -- it returns the previous value.
This is necessary to ensure another thread didn't write a different value just after you did.  For example, say you're trying to increment a variable.  You can read the value, add 1, then set the new value with
```
InterlockedExchange
```
.  The value returned by
```
InterlockedExchange
```
must match the value you originally read, otherwise another thread probably incremented it at the same time, and you need to loop around and try again.