How does memory barrier work?

assembly, c, c++, execution, instructions

Solution

`_ReadBarrier`, `_WriteBarrier`, and `_ReadWriteBarrier` are intrinsics that affect how the compiler can reorder code; they have absolutely nothing to do with CPU memory barriers and are only valid for specific kinds of memory (see "Affected Memory" here).

`MemoryBarrier()` is the intrinsic that you use to force a CPU memory barrier. However, the recommendation from Microsoft is to use `std::atomic<T>` going forward with VC++.

Problem

Under Windows, there are three compiler-intrinsic functions to implement memory barrier: ``` 1. _ReadBarrier; 2. _WriteBarrier; 3. _ReadWriteBarrier; ``` However, I found a weird problem: _ReadBarrier seems a dummy function doing nothing! The following is my assembly code generated by VC++ 2012. My question is: How to implement a memory barrier function in assembly instructions? ``` int main() { 013EEE10 push ebp 013EEE11 mov ebp,esp 013EEE13 sub esp,0CCh 013EEE19 push ebx 013EEE1A push esi 013EEE1B push edi 013EEE1C lea edi,[ebp-0CCh] 013EEE22 mov ecx,33h 013EEE27 mov eax,0CCCCCCCCh 013EEE2C rep stos dword ptr es:[edi] int n = 0; 013EEE2E mov dword ptr [n],0 n = n + 1; 013EEE35 mov eax,dword ptr [n] 013EEE38 add eax,1 013EEE3B mov dword ptr [n],eax _ReadBarrier(); n = n + 1; 013EEE3E mov eax,dword ptr [n] 013EEE41 add eax,1 013EEE44 mov dword ptr [n],eax } 013EEE56 xor eax,eax 013EEE58 pop edi 013EEE59 pop esi 013EEE5A pop ebx 013EEE5B add esp,0CCh 013EEE61 cmp ebp,esp 013EEE63 call __RTC_CheckEsp (013EC3B0h) 013EEE68 mov esp,ebp 013EEE6A pop ebp 013EEE6B ret ```

Original source