Assume you've got the following definitions:
struct X
{
char a, b;
};
X x;
And now assume you have two threads, one of which reads and writes x.a
but never accesses x.b
while the other one reads and writes x.b
but never accesses x.a
. Neither thread uses any locks or other synchronization primitives. Is this guaranteed to work in C++11? Or does it count as accessing the same object, and therefore need a lock?
Not only are different cores allowed to read from the same block of memory, they're allowed to write at the same time too.
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].
It's safe. Quoting C++11:
[intro.memory]p3:
A memory location is either an object of scalar type or a maximal sequence of adjacent bit-fields all having non-zero width. [ Note: Various features of the language, such as references and virtual functions, might involve additional memory locations that are not accessible to programs but are managed by the implementation. —end note ] Two threads of execution (1.10) can update and access separate memory locations without interfering with each other.
[intro.memory]p5:
[ Example: A structure declared as
struct {
char a;
int b:5,
c:11,
:0,
d:8;
struct {int ee:8;} e;
}
contains four separate memory locations: The field
a
and bit-fieldsd
ande.ee
are each separate memory locations, and can be modified concurrently without interfering with each other. The bit-fieldsb
andc
together constitute the fourth memory location. The bit-fieldsb
andc
cannot be concurrently modified, butb
anda
, for example, can be. —end example ]
These together mean that the members a
and b
of X
are separate memory locations, and can thus be accessed concurrently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With