[英]Can GCC use read-modify-write instructions to update volatile variables?
Suppose you have C code for x86 systems code like this: 假设您有x86系统代码的C代码,如下所示:
volatile uint32_t *reg = (volatile uint32_t *)0xCAFEBABE;
// ...
reg[0x10] |= 1;
Is GCC free to generate a read-modify-write instruction here? GCC可以在这里自由生成读 - 修改 - 写指令吗? If so, will encapsulating the read and write to the volatile variable in functions make sure that GCC does not combine the accesses into a single RMW instruction? 如果是这样,将封装读取和写入函数中的volatile变量确保GCC不将访问组合到单个RMW指令中?
I know that the C spec is intentionally vague about this. 我知道C规范对此有意模糊。
The C standard does not specify what instruction is to be used. C标准没有规定使用什么指令。 For a simple update like this gcc
is most liklely to generate a single RMW instruction the style of 对于像这样的简单更新, gcc
最有可能生成单个RMW指令的样式
orl (%rdx), $1
The volatile
keyword has nothing to do with it though. volatile
关键字与它无关。 any combination of load, modify, store
would have been valid too. load, modify, store
任何组合也都是有效的。 The volatile
keyword only tells the compiler to reload the value from memory on every use instead of using register caching optimisations. volatile
关键字仅告诉编译器在每次使用时从内存重新加载值,而不是使用寄存器缓存优化。
If you want an atomic update then you need atomics, gcc provides for this _sync_fetch_and_or(type *, type)
如果你想要原子更新,那么你需要原子,gcc提供了这个_sync_fetch_and_or(type *, type)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.