Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can C++ compilers support C++11 atomic, but not support C++11 memory model

While looking at Clang and g++ C++11 implementation status I noticed something strange:
they support C++11 atomics, but they dont support C++11 memory model.
I was under impression that you must have C++11 memory model to use atomics. So what exactly is the difference between support for atomics and memory model?
Does a lack of memory model support means that legal C++11 programs that use std::atomic<T> arent seq consistent?

references:
http://clang.llvm.org/cxx_status.html
http://gcc.gnu.org/gcc-4.7/cxx0x_status.html

like image 699
NoSenseEtAl Avatar asked Jul 02 '12 12:07

NoSenseEtAl


People also ask

What is memory model in C ++ 11?

C++11 Memory Model. A memory model, a.k.a memory consistency model, is a specification of the allowed behavior of multithreaded programs executing with shared memory [1].

Is volatile atomic in C?

In C and C++Operations on volatile variables are not atomic, nor do they establish a proper happens-before relationship for threading.


1 Answers

One of the issues is the definition of "memory location", that allows (and forces the compiler to support) locking different structure members by different locks. There is a discussion about a RL problem caused by this.

Basically the issue is that having a struct defined like this:

struct x {     long a;     unsigned int b1;     unsigned int b2:1; }; 

the compiler is free to implement writing to b2 by overwriting b1 too (and apparently, judging from the report, it does). Therefore, the two fields have to be locked as one. However, as a consequence of the C++11 memory model, this is forbidden (well, not really forbidden, but the compiler must ensure simultaneous updates to b1 and b2 do not interfere; it could do it by locking or CAS-ing each such update, well, life is difficult on some architectures). Quoting from the report:

I've raised the issue with our GCC guys and they said to me that: "C does not provide such guarantee, nor can you reliably lock different structure fields with different locks if they share naturally aligned word-size memory regions. The C++11 memory model would guarantee this, but that's not implemented nor do you build the kernel with a C++11 compiler."

Nice info can also be found in the wiki.

like image 179
jpalecek Avatar answered Oct 10 '22 01:10

jpalecek