I have a Windows 7 driver where I want to synchronize access to a variable. Can I use InterlockedExchange for it?
Maybe. Maybe not. It depends on what you are trying to do, what the variable represents and what your expectations are when you say "synchronize access".
With that said, I suspect the answer is no because I can't see how what you are doing counts as synchronization.
That means, the read (InterlockedExchange returns the old value) and the write is done in one clock cycle.
Not exactly. The interlocked functions ensure that the operation happens atomically. How many clock cycles that takes is another issue. Forget about clock cycles.
The interlocked functions are atomic only when the variable is always accessed via an interlocked function.
What does that even mean?
Does the function notice that the variable is accessed and defer the write to a different clock cycle?
It's more accurate to say that the processor notices, which it does. Whether it defers one write to a different clock cycle, what do you care? Maybe it does, maybe it doesn't. It's none of your business what the process does.
All the compiler and processor will guarantee in your example and all that you need to know is that:
- after the statement
InterlockedExchange(&Adapter->StatusVariable, 3);
the value ofAdapter->StatusVariable
will either be 3 or 5; and - after the statement
InterlockedExchange(&Adapter->StatusVariable, 5);
the value ofAdapter->StatusVariable
will either be 3 or 5.
It will have one of those two values and no other values. You just cannot know which of those values it will have and it should be obvious to see why that is.
Or is it undefined which value the variable has after the write?
That depends on your definition of "undefined" I guess. It's unclear which of the two values it will have, but it have either 3
or 5
assuming no other threads are changing the value after that point.
Is it also possible that the variable contains garbage?
If by 'garbage' you mean something other than either 3
or 5
then, in the absence of any other code that messes with the value, the answer is an unequivocal no. The variable will contain either the value 3
or the value 5
.