是否可以进行此编译器转换? [英] Is this compiler transformation allowed?
问题描述
考虑以下代码,其中x
和y
是整数:
Consider this code, where x
and y
are integers:
if (x)
y = 42;
是否允许以下编译器转换?
Is the following compiler transformation allowed ?
int tmp = y;
y = 42;
if (!x)
y = tmp;
上下文:
这是来自Bjarne Stroustrup的常见问题解答:
This is from Bjarne Stroustrup's FAQ:
// start with x==0 and y==0
if (x) y = 1; // Thread 1
if (y) x = 1; // Thread 2
常见问题解答指出这是免费的数据竞赛;如果x
和y
均为0,则不应将任何var写入.
但是,如果允许转换怎么办?
The FAQ states this is data race free; with x
and y
both 0, none of the vars should be written to.
But what if the transformation is allowed ?
推荐答案
与我在不正确的注释中写的不同,如果y
可能在线程之间共享,并且编译器无法证明线程中存在任何现有的UB,则实际上不允许这种转换.原始代码.
Unlike I wrote in my incorrect comment, this transformation is actually not allowed if y
is potentially shared between threads and the compiler cannot prove any existing UB in the original code.
该标准明确规定:
编译器转换,将分配引入到潜在的共享内存位置,该位置 不会被抽象机器修改的对象通常会被该标准排除,因为这样的 在抽象机器的情况下,分配可能会通过不同的线程覆盖另一个分配 执行过程不会遇到数据争用.
Compiler transformations that introduce assignments to a potentially shared memory location that would not be modified by the abstract machine are generally precluded by this standard, since such an assignment might overwrite another assignment by a different thread in cases in which an abstract machine execution would not have encountered a data race.
N3337中的[intro.multithread](1.10/22),N4141中的(1.10/25).
[intro.multithread] (1.10/22) in N3337, (1.10/25) in N4141.
因此,如果x
始终为0,则原始代码将是无竞争的,而转换后的代码则不会.因此,这种转换是不合法的.
So if x
is always 0, the original code would be race-free, while the transformed one wouldn't. Thus the transformation is not legal.
这篇关于是否可以进行此编译器转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!