Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should the Win32 InterlockedExchange function be used?

I came across the function InterlockedExchange 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?
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)

like image 882
EFrank Avatar asked Oct 16 '08 13:10

EFrank


2 Answers

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.

like image 55
Jason Cohen Avatar answered Sep 20 '22 22:09

Jason Cohen


As well as writing the new value, InterlockedExchange also reads and returns the previous value; this whole operation is atomic. This is useful for lock-free algorithms.

(Incidentally, 32-bit writes are not guaranteed to be atomic. Consider the case where the write is unaligned and straddles a cache boundary, for instance.)

like image 24
moonshadow Avatar answered Sep 16 '22 22:09

moonshadow