我试图编写一些代码来观察内存操作的重新排序。
在下面的示例中,我希望在执行set_values()时可以更改分配值的顺序。特别地,通知= 1可能在其余操作之前发生,但是即使在thousens迭代之后也没有发生。 我已经使用-O3优化来编译代码。 这是我指的YouTube资料: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之前执行,这将触发execute()函数的执行,并给出a == 3满足终止循环并证明重新排序的条件
或者也许有人可以提供其他琐碎的代码示例来帮助观察内存操作的重新排序?