1

我对 C++11 功能std::async很陌生,我无法理解为什么下面的代码从不打印bar

有人可以为我解释一下吗?

class Thready {

  public:

    Thready() {
        std::async(std::launch::async, &Thready::foo, this);
    }

    void foo() {
        while (true) {
            std::cout << "foo" << std::endl;
        }
    }

    void bar() {
        while (true) {
            std::cout << "bar" << std::endl;
       }
    }
};

int main() {  
    Thready t;
    t.bar();
}
4

1 回答 1

2

请参阅此页面上的“注释”部分:http: //en.cppreference.com/w/cpp/thread/async

该实现可以通过在默认启动策略中启用额外的(实现定义的)位来扩展 std::async 的第一次重载的行为。实现定义的启动策略的示例是同步策略(立即执行,在异步调用中)和任务策略(类似于异步,但线程本地不清除)如果从 std::async 获得的 std::future 是没有从引用移动或绑定到引用,std::future 的析构函数将在完整表达式的末尾阻塞,直到异步操作完成,本质上使代码如下同步:

std::async(std::launch::async, []{ f(); }); // temporary's dtor waits for f()
std::async(std::launch::async, []{ g(); }); // does not start until f() completes

(请注意,通过调用 std::async 以外的方式获得的 std::futures 的析构函数永远不会阻塞)

TL;博士:

尝试将 std::async 调用的返回值保存到某个变量中:

auto handle = std::async(std::launch::async, &Thready::foo, this);

编辑:

以下代码应该可以按您的预期工作。

#include <future>
#include <iostream>

class Thready {

  public:

    Thready() {
        handle = std::async(std::launch::async, &Thready::foo, this);
    }

    void foo() {
        while (true) {
            std::cout << "foo" << std::endl;
        }
    }

    void bar() {
        while (true) {
            std::cout << "bar" << std::endl;
       }
    }

    std::future<void> handle;
};

int main() {  
    Thready t;
    t.bar();
}
于 2016-10-13T20:45:38.053 回答