gpt4 book ai didi

c - cpu 会将 STORE 指令重新排序到同一地址吗?

转载 作者:太空宇宙 更新时间:2023-11-04 06:12:15 26 4
gpt4 key购买 nike

给出下面的代码,CPU 会重新排序 STORE a 和 STORE b 吗?从代码逻辑上看,a和b是独立的。

int* __attribute__ ((noinline)) GetMemAddr(int index) {
static int data[10];
return &data[0];
}

void fun() {
int *a=GetMemAddr(1); //use different args to get same address to avoid optimiztion
int *b=GetMemAddr(2);
*a=1;
*b=3;
}

最佳答案

你现在的问题几乎毫无意义。

int* __attribute__ ((noinline)) GetMemAddr(int index) {
static int data[10];
return &data[0];
}

void fun() {
int *a=GetMemAddr(1); //use different args to get same address to avoid optimiztion
int *b=GetMemAddr(2);
*a=1;
*b=3;
}

这个compiled with GCC 7.3 and -O3完全省略了对 GetMemAddr 的第一次调用,因为它没有副作用。它也省略了赋值 *a=1noinline 表示该函数不得内联。这并不意味着它根本不需要调用。

真正避免省略的唯一正确方法是将 ab 声明为 volatile int *。这样,商店也将保持秩序。然而,仍然无法以任何方式保证这些存储是原子,因此另一个线程可以看到有趣的事情发生 - 对于那些您需要使用 C11 原子特性或编译器扩展/保证的线程。

关于c - cpu 会将 STORE 指令重新排序到同一地址吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53845062/

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