【问题标题】:C++ std::async does not spawn a new threadC++ std::async 不会产生新线程
【发布时间】:2017-02-09 05:08:07
【问题描述】:

C++11

int main(int argc, char** argv) {
    std::async(std::launch::async, [](){ 
        while(true) cout << "async thread" <<endl; 
    });
    while(true) cout << "main thread" << endl;
    return 0;
}

我预计输出应该与 async threadmain thread 交错,因为应该有 2 个不同的线程。

但事实并非如此。

它输出:

async thread
async thread
async thread
async thread
...

我猜只有一个线程。有人能告诉我为什么它没有为std::async 生成一个新线程吗?谢谢。

【问题讨论】:

标签: c++ multithreading asynchronous stdasync


【解决方案1】:

改成这样:

auto _ = std::async(std::launch::async, [](){ 
    while(true) cout << "async thread" <<endl; 
});

文档:

如果从 std::async 获得的 std::future 没有被移出或绑定 对于引用,std::future 的析构函数将在 完整表达式的结尾,直到异步操作完成, 本质上是使如下代码同步:

std::async(std::launch::async, []{ f(); }); // 临时的 dtor 等待 对于 f() std::async(std::launch::async, []{ g(); }); // 不启动 直到 f() 完成

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-13
    • 2021-11-24
    • 2023-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多