繁体   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