1
votes

Is concurrent non-atomic read and write on variables of C++ fundamental types (multiple reads and multiple writes) an undefined behavior in C++? I don't care about the actual value, as later I will find out if concurrent read/write has happened and if so, I ignore the current value. I just want to know if the behavior is well-defined C++?

If it is well-defined, is it still well defined if Thread 1 reads/writes x and Thread 2 reads/writes y in, where x and y are members of the following union?

union {
  int x;
  double y;
};
2
It is undefined, that's why you use atomic operations which locks that portion of memory from being accessed by another thread until you complete your operation. - Irelia
Do a little reading on the C++ Memory Model and Union. - Fred Larson

2 Answers

10
votes

Is concurrent non-atomic read and write on variables of C++ fundamental types (multiple reads and multiple writes) an undefined behavior in C++?

Yes. The standard (quote from latest draft) says:

[intro.races]

The execution of a program contains a data race if it contains two potentially concurrent conflicting actions, at least one of which is not atomic, and neither happens before the other, except for the special case for signal handlers described below. Any such data race results in undefined behavior. ...


just want to know if the behavior is well-defined C++?

It is undefined.

if Thread 1 reads/writes x and Thread 2 reads/writes y in, where x and y are members of the following union?

This is potentially even "more" undefined, because not only is there a data race, but also there is potential that value of an inactive member of the union is read.

0
votes

Although the standard fails to define most things regarding multithreading (not even what is sequential and what is not is defined) but one thing is clear: you are not supposed to write to any variable that you use in any way "at the same time": you must use a mutual exclusion primitive to make modifications to variable well ordered.