簡體   English   中英

為什么即使使用指定的std :: launch :: async標志,std :: async也會同步調用該函數

[英]Why does std::async call the function synchronously even with the specified std::launch::async flag

我傳遞給std :: async的函數打印當前的線程ID。 盡管使用std :: launch :: async標志進行調用,但它會打印相同的thead id。 這意味着它同步調用該函數。 為什么?

void PrintThreadId()
{
    std::cout << std::this_thread::get_id() << std::endl;
}

int main()
{
    for (int i = 0; i < 5; ++i)
    {
        auto f = std::async(std::launch::async, PrintThreadId);
        f.wait();
    }
}

輸出為:20936 20936 20936 20936 20936

環境:VS 2015,W7。

先感謝您!

實際上,您通過等待每個調用來序列化調用,因此可以重用相同的線程,而不會破壞std::future由與調用者線程不同的線程執行的規范

當以下代碼與其余代碼顯示相同的Caller ThreadId時喚醒我們:

void PrintThreadId()
{
    std::cout << std::this_thread::get_id() << std::endl;
}

int main()
{
    std::cout << "Caller threadId (to be different from any id of the future exec thread): ";
    PrintThreadId();

    for (int i = 0; i < 5; ++i)
    {
        auto f = std::async(std::launch::async, PrintThreadId);
        f.wait();
    }
}

您未來的生命周期以函數的每次迭代的范圍結束。 與之相關的線程也會消失。 該實現可以在以后自由地重用它,即在循環的下一次迭代中。

如果您修改示例代碼以打印當前線程ID,您將看到當前線程不同:

for (int i = 0; i < 5; ++i)
{
    PrintThreadId();
    auto f = std::async(std::launch::async, PrintThreadId);
    f.wait();
}

現場演示

您還應該考慮返回async期貨是特殊的 - 在析構函數中它們會阻塞,直到任務未完成。 關於Scott Meyers博客的更多信息,相反標題: 來自std::async std::futures並不特別

暫無
暫無

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

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