2

In C, is there a compiler-neutral way to issue a compiler-level memory barrier, like gcc's asm volatile ("" ::: "memory");? The exact behaviour that I want is to prevent the compiler from re-ordering memory accesses across the barrier (so if a value is copied to a register before the barrier, I want to make sure it is re-read from memory after the barrier). I'm thinking that stdatomic.h's atomic_signal_fence or atomic_thread_fence might be able to achieve this, but I'm not familiar enough with them to know for sure. Thanks.

Harris M Snyder
  • 274
  • 1
  • 8
  • 1
    C and C++ are different languages, but it's really the same question as [Is there any compiler barrier which is equal to asm("" ::: "memory") in C++11?](https://stackoverflow.com/q/40579342) because real-world compilers handle C11 `atomic_signal_fence` identically to C++11 `std::atomic_signal_fence`, and generally work the same way wrt. local variables and escape analysis, etc. – Peter Cordes Oct 01 '21 at 21:06
  • 1
    And either way https://lwn.net/Articles/793253/ applies; using barriers to force reloads of non-`_Atomic` variables isn't as safe as using two separate read-once operations. (Unless you're just barriering between two `memory_order_relaxed` loads, e.g. for a seqlock, that's sensible.) – Peter Cordes Oct 01 '21 at 21:06
  • Is there any reason why there shouldn't be a standard means of placing a compiler-level reordering barrier in cases where a programmer knows that doing so would be necessary and sufficient to accomplish what needs to be done (e.g. because the programmer did whatever is necessary to manipulate the execution environment so all execution contexts that access shared objects will be run in the same core, or configured the region of address space holding shared objects to disable caching, etc.)? – supercat Nov 01 '21 at 22:19

0 Answers0