I'm reading a legacy C++ code where memory barrier is defined as below. The main OS are linux and vxworks. The compilers are gcc(WindRiver's gcc).
#if((KCompilerGNU)||(kCompilerWindRiver))
#define MEMORY_BARRIER __asm__ volatile("nop\n");
#else
#define MEMORY_BARRIER __asm nop;
#endif
But I don't see how a no-op operation works to produce a memory barrier? Or it's just a fault implementation?
This is a compiler barrier, not a full hardware memory barrier. That is, it is intended to be an opaque call that the compiler can't optimize across, but it doesn't have any effect on the hardware in terms of memory re-ordering1. It may be defined correctly for that purpose if the compilers in question do in fact treat asm blocks as opaque (for example, gcc asm blocks have specific rules for defining exactly what can change across a block, etc).
It may be appropriate to call it a full memory barrier (which usually suppresses both compiler and hardware re-orderings) if you know the hardware this code targets has a strong memory model that never reorders memory operations.
1 That said, such a barrier could still be sufficient in the case that the program is single-threaded or the machine doesn't exhibit interesting reorderings (e.g., a simple in-order, non-speculative CPU or a single-CPU system).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With