在构造函数中使用std :: async [英] Using std::async in constructor
问题描述
我对C ++ 11功能 std :: async
还是很陌生,我无法理解为什么下面的代码从不打印 bar
.
I am quite new to the C++11 feature std::async
and I fail to grasp why the code below never prints 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();
}
推荐答案
请参阅此页上的注释"部分: http://en.cppreference.com/w/cpp/thread/async
See "Notes" section on this page: http://en.cppreference.com/w/cpp/thread/async
该实现可能会扩展的第一个重载的行为std :: async通过启用附加的(实现定义的)位来实现默认启动策略.实施定义的启动示例策略是同步策略(在异步内立即执行调用)和任务策略(类似于异步,但线程本地不是)(清除)如果从std :: async获得的std :: future没有从或绑定到引用,则std :: future的析构函数将阻止在完整表达式的末尾直到异步操作完成后,基本上使诸如以下代码的代码同步:
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
(请注意,std :: futures的析构函数通过对std :: async的调用之外的其他方式获得,从不阻止)
(note that the destructors of std::futures obtained by means other than a call to std::async never block)
TL; DR:
尝试将std :: async调用的返回值保存到某个变量中:
try to save the returned value of std::async call into some variable:
auto handle = std::async(std::launch::async, &Thready::foo, this);
以下代码应该可以正常工作.
the following code should work as you expect.
#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();
}
这篇关于在构造函数中使用std :: async的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!