在构造函数中使用 std::async

Using std::async in constructor

我对 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();
}

请参阅本页的 "Notes" 部分:http://en.cppreference.com/w/cpp/thread/async

The implementation may extend the behavior of the first overload of std::async by enabling additional (implementation-defined) bits in the default launch policy. Examples of implementation-defined launch policies are the sync policy (execute immediately, within the async call) and the task policy (similar to async, but thread-locals are not cleared) If the std::future obtained from std::async is not moved from or bound to a reference, the destructor of the std::future will block at the end of the full expression until the asynchronous operation completes, essentially making code such as the following synchronous:

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

(note that the destructors of std::futures obtained by means other than a call to std::async never block)

TL;DR:

尝试将 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();
}