是否确保保留对易失性结构的单独成员的写入顺序? [英] Is the order of writes to separate members of a volatile struct guaranteed to be preserved?

查看:54
本文介绍了是否确保保留对易失性结构的单独成员的写入顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的结构:

Suppose I have a struct like this:

volatile struct { int foo; int bar; } data;
data.foo = 1;
data.bar = 2;
data.foo = 3;
data.bar = 4;

是否保证所有作业都不会重新排序?

Are the assignments all guaranteed not to be reordered?

例如,在没有volatile的情况下,显然可以允许编译器将其作为两条指令以不同的顺序进行优化,如下所示:

For example without volatile, the compiler would clearly be allowed to optimize it as two instructions in a different order like this:

data.bar = 4;
data.foo = 3;

但是对于volatile,是否要求编译器不要执行此类操作?

But with volatile, is the compiler required not to do something like this?

data.foo = 1;
data.foo = 3;
data.bar = 2;
data.bar = 4;

(将成员作为单独的不相关的易失性实体进行处理-并进行重新排序,我可以想象它可能会尝试在 foo bar 位于页面边界-例如.

(Treating the members as separate unrelated volatile entities - and doing a reordering that I can imagine it might try to improve locality of reference in case foo and bar are at a page boundary - for example.)

此外,答案是否与C和C ++标准的当前版本一致?

Also, is the answer consistent for current versions of both C and C++ standards?

推荐答案

它们不会重新排序.

C17 6.5.2.3(3)说:

C17 6.5.2.3(3) says:

后缀表达式,后跟.运算符和标识符指定结构的成员或并集对象.该值是指定成员的值(97),如果第一个表达式是一个左值.如果第一个表达式具有限定类型,则结果具有该类型的限定版本的指定成员.

A postfix expression followed by the . operator and an identifier designates a member of a structure or union object. The value is that of the named member, 97) and is an lvalue if the first expression is an lvalue. If the first expression has qualified type, the result has the so-qualified version of the type of the designated member.

由于 data 具有 volatile 限定的类型,所以 data.bar data.foo 也是如此.因此,您要对 volatile int 对象执行两次分配.还有6.7.3脚注136,

Since data has volatile-qualified type, so do data.bar and data.foo. Thus you are performing two assignments to volatile int objects. And by 6.7.3 footnote 136,

对这样声明为[as volatile ]的对象的操作不应被优化"实现或重新排序,除非评估表达式的规则允许.

Actions on objects so declared [as volatile] shall not be "optimized out" by an implementation or reordered except as permitted by the rules for evaluating expressions.

一个更微妙的问题是,编译器是否可以通过一条指令将它们都赋值,例如,如果它们是连续的32位值,是否可以使用64位存储来设置两者?我认为不会,至少GCC和Clang不会尝试.

A more subtle question is whether the compiler could assign them both with a single instruction, e.g., if they are contiguous 32-bit values, could it use a 64-bit store to set both? I would think not, and at least GCC and Clang don't attempt to.

这篇关于是否确保保留对易失性结构的单独成员的写入顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆