The MSDN docs for "volatile" in Visual C++ indicate that writes have "release semantics开发者_如何转开发" and that reads have "acquire semantics", in addition to ensuring that reads always read from memory and that writes always write accordingly.
The C spec for "volatile" includes the second part (don't do crazy optimizations), but not the first part (a memory fence).
Is there any way in Visual C++ to get the "C" volatile behaviour only, without the memory fence?
I want to force a variable to always be on the stack, in a fixed spot, but I don't want to take the overhead of a memory fence on every assignment to it.
Is there any easy way to do that with Visual C++ source?
Is there any way in Visual C++ to get the "C" volatile behaviour only, without the memory fence?
On x86 there are no memory fences created at the assembly level on reads and writes to a volatile
memory location since on that platform every load has acquire semantics, and every store has release semantics. Therefore for MSVC on x86, the volatile
directive simply directs the compiler to prevent the reordering of loads and stores depending on if you are writing or reading from the memory location that was marked volatile
.
You would only incur the "penalty" of a memory fence on the IA64 architecture, since there the memory ordering model of the platform does not ensure acquire and release semantics for loads and stores.
Keep in mind this behavior is MSVC-specific, and is not a standardized semantic of volatile
.
Update: According to @ildjarn you would also see a memory fence on ARM with Windows 8 since that platform also has a weakly ordered memory-consistency model like IA64.
精彩评论