下面的 async
调用正在阻塞,因为返回的 future 的析构函数正在阻塞:
void foo() {}
void foo_async() {
std::async(std::launch::async, foo);
}
但我不想阻止!
我正在考虑使用以下解决方法:
void foo_async() {
std::thread(foo).detach();
}
这样好吗?或者您会推荐其他解决方案吗?
最佳答案
您可以使用以下版本的异步,它提供了一个非阻塞的 future 。因此,如果您需要,您可以利用 future ,另一方面,当您想要一个即发即弃的任务时,您可以忽略它。
template< class Function, class... Args>
std::future<typename std::result_of<Function(Args...)>::type> async( Function&& f, Args&&... args )
{
typedef typename std::result_of<Function(Args...)>::type R;
auto bound_task = std::bind(std::forward<Function>(f), std::forward<Args>(args)...);
std::packaged_task<R()> task(std::move(bound_task));
auto ret = task.get_future();
std::thread t(std::move(task));
t.detach();
return ret;
}
关于c++ - 阻止异步的解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16296284/