是否确保保留对易失性结构的单独成员的写入顺序?

编程入门 行业动态 更新时间:2024-10-20 05:31:29
本文介绍了是否确保保留对易失性结构的单独成员的写入顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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?

推荐答案

c

它们不会重新排序.

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.

更多推荐

是否确保保留对易失性结构的单独成员的写入顺序?

本文发布于:2023-10-16 16:32:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1498115.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:顺序   成员   结构   易失性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!