我正在试验 C++0x 支持,但有一个问题,我想不应该存在。要么我不理解这个主题,要么 gcc 有一个错误。
我有以下代码,最初x
并且y
是相等的。线程 1 总是x
先递增,然后递增y
。两者都是原子整数值,因此增量完全没有问题。线程 2 正在检查 是否x
小于y
,如果是则显示错误消息。
此代码有时会失败,但为什么呢?这里的问题可能是内存重新排序,但默认情况下所有原子操作都是顺序一致的,我没有明确放宽这些操作。我正在 x86 上编译这段代码,据我所知,它不应该有任何排序问题。你能解释一下问题是什么吗?
#include <iostream>
#include <atomic>
#include <thread>
std::atomic_int x;
std::atomic_int y;
void f1()
{
while (true)
{
++x;
++y;
}
}
void f2()
{
while (true)
{
if (x < y)
{
std::cout << "error" << std::endl;
}
}
}
int main()
{
x = 0;
y = 0;
std::thread t1(f1);
std::thread t2(f2);
t1.join();
t2.join();
}
结果可以在这里查看。