gpt4 book ai didi

c++ - 重新排序内存操作的简单示例

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

我试图编写一些代码来观察内存操作的重新排序。

在下面的示例中,我预计在执行 set_values() 时,赋值的顺序可能会发生变化。特别是 notification = 1 可能发生在其余操作之前,但即使经过几千次迭代也不会发生。我用 -O3 优化编译了代码。这是我指的 youtube Material :https://youtu.be/qlkMbxUbKfw?t=200

int a{0};
int b{0};
int c{0};
int notification{0};

void set_values()
{
a = 1;
b = 2;
c = 3;
notification = 1;
}

void calculate()
{
while(notification != 1);
a += b + c;
}

void reset()
{
a = 0;
b = 0;
c = 0;
notification = 0;
}

int main()
{
a=6; //just to allow first iteration

for(int i = 0 ; a == 6 ; i++)
{
reset();
std::thread t1(calculate);
std::thread t2(set_values);

t1.join();
t2.join();
std::cout << "Iteration: " << i << ", " "a = " << a << std::endl;
}
return 0;
}

现在程序陷入了死循环。我希望在某些迭代中 set_values() 函数中的指令顺序可以改变(由于对现金存储器的优化)。例如 notification = 1 会在 c = 3 之前执行 what 会触发 calculate() 函数的执行并给出 a==3 what 满足终止循环并证明重新排序的条件

或者也许有人可以提供其他简单的代码示例来帮助观察内存操作的重新排序?

最佳答案

编译器确实可以在函数 set_values 中重新排序您的赋值。但是,不需要这样做。在这种情况下,它没有理由重新排序任何东西,因为您正在为所有四个变量分配常量。

Now the program is stuck in infinited loop.

这可能是因为 while(notification != 1); 会被优化为死循环。

通过一些工作,我们可以找到一种方法让编译器在其他语句之前重新排序赋值 notify = 1,请参阅 https://godbolt.org/z/GY-pAw .请注意,程序从标准输入读取 x,这样做是为了强制编译器从内存位置读取。

我还使变量 notification 可变,这样 while(notification != 1); 就不会被优化掉。

您可以在您的机器上尝试这个示例,我一直能够使用在 Intel Sandy Bridge cpu 上运行的 g++9.2 和 -O3 使断言失败。

请注意,如果指令彼此独立,则 cpu 本身可以重新排序指令,请参阅 https://en.wikipedia.org/wiki/Out-of-order_execution .但是,要始终如一地进行测试和重现,这有点棘手。

关于c++ - 重新排序内存操作的简单示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58719811/

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