Intel® Moderncode for Parallel Architectures
Support for developing parallel programming applications on Intel® Architecture.
Announcements
Welcome to the Intel Community. If you get an answer you like, please mark it as an Accepted Solution to help others. Thank you!

Memory fences

Tudor
New Contributor I
86 Views
Hello,

Just a quick question regarding memory fences in C.
What exactly is the difference (if any) between:
__sync_synchronize();
asm volatile("":::"memory");
0 Kudos
1 Reply
anthony_williams
Beginner
86 Views
asm volatile("":::"memory"); merely prevents the compiler's optimizer from rearranging your code --- reads and writes that appear in source before that asm block must appear as CPU instructions before that asm block, and reads and writes that appear in source after that asm block must appear as CPU instructions after that asm block. The CPU may still reorder these reads and writes, and they may become visible to other CPUs in the system out of order (but constrained by the CPU memory model).

__sync_synchronize() will generate a suitable CPU instruction to generate a memory fence. On Intel CPUs this may be an MFENCE instruction, or a LOCKed instruction such as XCHG. This has the additional consequence of imposing visibility constraints on the memory accesses at the CPU level.
Reply