简体   繁体   中英

Is Concurrent Non-Atomic Read/Write An Undefined Behavior?

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;
};

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.

尽管该标准未能定义有关多线程的大多数内容(甚至没有定义什么是顺序的,什么是未定义的),但有一点很清楚:您不应该“同时”以任何方式写入您使用的任何变量:您必须使用互斥原语来修改有序的变量。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM