Is there a compiler memory barrier for a single variable?

后端 未结 4 1567
长情又很酷
长情又很酷 2021-01-02 08:45

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 t

相关标签:
4条回答
  • 2021-01-02 09:00

    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))
    
    0 讨论(0)
  • 2021-01-02 09:10

    Try with { int y = x; *(volatile int*)&x = y; } and inspect the resulting assembly.

    0 讨论(0)
  • 2021-01-02 09:10

    I guess you can achieve it by specifying your variable in the list of output values of asm:

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

    See Extended Asm for some information.

    UPD.

    It may be better to use "g" constraint instead of "r" as more permissive.

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

    Also, I've found another great howto for inline assembly.

    0 讨论(0)
  • 2021-01-02 09:20

    Since you are willing to work with gcc extensions you could use the extensions for atomic instructions for that feature:

    __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)
提交回复
热议问题