C++11 memory model and accessing different members of the same struct in different threads C++11 memory model and accessing different members of the same struct in different threads multithreading multithreading

C++11 memory model and accessing different members of the same struct in different threads


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-fields d and e.ee are each separate memory locations, and can be modified concurrently without interfering with each other. The bit-fields b and c together constitute the fourth memory location. The bit-fields b and c cannot be concurrently modified, but b and a, 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.