简体   繁体   English

单个变量是否存在编译器内存障碍?

[英]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: 例如,GCC有以下声明:

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? 有没有办法告诉编译器(特别是GCC,但我也对其他人感兴趣)只对特定变量做同样的效果? 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. 具有预期的行为,即x和x的值仅被写入相应的存储器位置,如果它恰好被缓存在寄存器中。

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! 提前致谢!

Try with { int y = x; *(volatile int*)&x = y; } 试试{ int y = x; *(volatile int*)&x = y; } { int y = x; *(volatile int*)&x = y; } { int y = x; *(volatile int*)&x = y; } and inspect the resulting assembly. { int y = x; *(volatile int*)&x = y; } ,并检查所得到的组件。

Since you are willing to work with gcc extensions you could use the extensions for atomic instructions for that feature: 由于您愿意使用gcc扩展,因此可以使用该功能的原子指令扩展:

__sync_bool_compare_and_swap(&myvar, 0, 0)

would set the value of the variable to 0 if it is already 0 :) and in addition imply a full sequential consistency on that memory location. 如果它已经是0 ,则将变量的值设置为0 ,并且另外暗示该内存位置的完全顺序一致性。

重新收集lkml上的一个线程,单变量仅编译器屏障的方法之一是:

#define forget(x) __asm__ __volatile__("":"=m"(x):"m"(x))

I guess you can achieve it by specifying your variable in the list of output values of asm : 我想你可以通过在asm的输出值列表中指定你的变量来实现它:

__asm__ __volatile__ ("" : "=r" (x) : : )

See Extended Asm for some information. 有关一些信息,请参阅Extended Asm

UPD. UPD。

It may be better to use "g" constraint instead of "r" as more permissive. 使用"g"约束而不是"r"作为更宽松的可能更好。

__asm__ __volatile__ ("" : "=g" (x) : : )

Also, I've found another great howto for inline assembly. 另外,我发现了内联装配的另一个很棒的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM