[英]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++?对 C++ 基本类型(多次读取和多次写入)的变量进行并发非原子读取和写入是 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++?
我只想知道行为是否是定义良好的 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
?如果定义良好,如果线程 1 读/写
x
和线程 2 读/写y
是否仍然定义良好,其中x
和y
是以下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++?
对 C++ 基本类型(多次读取和多次写入)的变量进行并发非原子读取和写入是 C++ 中的未定义行为吗?
Yes.是的。 The standard (quote from latest draft) says:
标准(引自最新草案)说:
[intro.races]
[介绍.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++?
只是想知道行为是否是定义良好的 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?
如果线程 1 读取/写入 x 并且线程 2 读取/写入 y,其中 x 和 y 是以下联合的成员?
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.这可能甚至“更多”未定义,因为不仅存在数据竞争,而且还可能读取联合的非活动成员的值。
尽管该标准未能定义有关多线程的大多数内容(甚至没有定义什么是顺序的,什么是未定义的),但有一点很清楚:您不应该“同时”以任何方式写入您使用的任何变量:您必须使用互斥原语来修改有序的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.