Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a compiler memory barrier for a single variable?

Compiler memory barriers has the effect among other things to force the compiler to make sure all stack variables that are cached in registers are written to memory before the barrier.

For example, GCC has the following statement:

asm inline ("" : : : "memory");

Is there any way to tell a compiler (specifically GCC, but I'm interested in others as well) to do the same effect for only a specific variable? something like the following imagined construct:

int x;
...
asm inline ("" : : : "memory(x)");

With the expected behavior that the value of x and x only will be written to the corresponding memory location, if it happens to be cached in a register.

The reason for this is that I have a specific variable which I need to make sure is not cached in a register so that a hardware engine can read its value. However, a full compiler memory barrier will force the compiler to write to memory the value of all other variables that might be cached in register at that point in time as well which can amount to much more data then I need to write. I wondered if there something more specific.

Thanks in advance!

like image 740
gby Avatar asked Jan 17 '12 14:01

gby


People also ask

What is a memory barrier in operating system?

(January 2016) A memory barrier, also known as a membar, memory fence or fence instruction, is a type of barrier instruction that causes a central processing unit (CPU) or compiler to enforce an ordering constraint on memory operations issued before and after the barrier instruction.

Why do we need memory barriers in C++?

It’s important to note, in general, memory barriers are needed for communication between different processors (There are exceptions of course, such as using a memory barrier to suppress the compiler or JIT optimizations). If the system has only one single processor, then there may not be a need for memory barriers.

What is a memory barrier instruction?

A memory barrier, also known as a membar, memory fence or fence instruction, is a type of barrier instruction that causes a central processing unit (CPU) or compiler to enforce an ordering constraint on memory operations issued before and after the barrier instruction.

Which effect is available before the memory barrier in processor 1?

Now, the effects before the memory barrier in processor 1 (STORE X = 1) are available after the barrier in processor 2 (LOAD X). Processors rely heavily on caches. It is in fact common for each core to have its own cache, and it is possible for some cores to share the same cache.


1 Answers

Recollecting one of the threads on lkml, one of the methods for single variable compiler-only barrier is:

#define forget(x) __asm__ __volatile__("":"=m"(x):"m"(x))
like image 126
Michal Soltys Avatar answered Oct 01 '22 20:10

Michal Soltys