在 C++ 中,std::atomic 会产生竞争条件。但是当使用 std::async 时,它会产生竞争条件

In C++, std::atomic generates race condition. But when using std::async, it generates race condition

在 C++ 中,std::atomic 生成竞争条件。但是当使用 std::async 时,它会产生竞争条件。

std::atomic<int> k = 0;


int func()
{
    for (int i=0; i < 1000000; i++)
    {
        k++;
    }
    return 1;
}

int main(void)
{
    auto fut  = std::async(launch::async, func);
    auto fut2 = std::async(launch::async, func);

    cout<<"k : "<<k<<endl;

    return 0;
}

结果不一致。

2000000
1983702
1970595
...

但是当使用std::thread时,它工作正常。

据我所知,std::atomic 保证没有竞争条件。 但为什么会这样?

您必须等到异步调用完成。

    fut.wait();
    fut2.wait();
    std::cout<<"k : "<<k<<std::endl;

在我的电脑上,我得到的代码总是 0!