请参阅此页面上的“注释”部分: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();
}