簡體   English   中英

在 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!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM