gpt4 book ai didi

c - 编译器可能不会跨序列点移动对 volatile 变量的访问;这是什么意思?

转载 作者:太空狗 更新时间:2023-10-29 17:23:02 29 4
gpt4 key购买 nike

将变量声明为“volatile”意味着直接从内存位置读取/写入,而不是从寄存器变量读取/写入。我了解“序列点”。但是我不明白标题中提到的声明。

谁能解释一下,并给出一些代码片段?

最佳答案

所有这些都在 C11 5.1.2.3 中描述

Program execution

/--/

Accessing a volatile object, modifying an object, modifying a file, or calling a function that does any of those operations are all side effects, which are changes in the state of the execution environment. Evaluation of an expression in general includes both value computations and initiation of side effects.

Sequenced before is an asymmetric, transitive, pair-wise relation between evaluations executed by a single thread, which induces a partial order among those evaluations. Given any two evaluations A and B, if A is sequenced before B, then the execution of A shall precede the execution of B. ...

The presence of a sequence point between the evaluation of expressions A and B implies that every value computation and side effect associated with A is sequenced before every value computation and side effect associated with B.

/--/

An actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no needed side effects are produced (including any caused by calling a function or accessing a volatile object).

/--/

The least requirements on a conforming implementation are:

— Accesses to volatile objects are evaluated strictly according to the rules of the abstract machine.

这不是很容易解释,但它在简单英语中的大致意思是:由于 volatile 对象的访问是一种副作用,因此不允许编译器优化此类访问,也不允许对其进行排序它们以不同的顺序排列,否则它可能会这样做,以便在具有指令缓存/分支预测的 CPU 上获得更好的性能,或者只是更好的性能,因为它具有方便地存储在某些 CPU 寄存器中的某些值。

(C11 标准还明确指出不保证 volatile 对象是线程安全的,上下文切换后 volatile 对象的值是未指定的行为。)

编辑一个例子

给定代码

volatile int x;
volatile int y;
volatile int z;

x=i;
y=something;
z=i;

则不允许编译器将可执行文件中的指令重新排序为

x=i;
z=i;
y=something

因为对 y 的访问必须在对 z 的访问之前排序。分号处有一个序列点。但是,如果变量不是 volatile 的,编译器可以确定重新排序它们不会影响程序的结果。

关于c - 编译器可能不会跨序列点移动对 volatile 变量的访问;这是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13197214/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com