Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this memory barrier implemented correctly?

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?

like image 980
Eric Z Avatar asked Feb 18 '23 15:02

Eric Z


1 Answers

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).

like image 125
BeeOnRope Avatar answered Feb 23 '23 01:02

BeeOnRope