C++ 何时使用 std::async 与 std::threads?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25814365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When to use std::async vs std::threads?
提问by Javi V
Can anybody give a high level intuition about when to use each of them?
任何人都可以就何时使用它们中的每一个给出高层次的直觉吗?
References:
参考:
采纳答案by mattnewport
It's not really an either-orthing - you can use futures (together with promises) with manually created std::threads. Using std::async
is a convenient way to fire off a thread for some asynchronous computation and marshal the result back via a future but std::async
is rather limited in the current standard. It will become more useful if the suggested extensions to incorporate some of the ideas from Microsoft's PPL are accepted.
这不是一个真正的非此即彼的事情 - 您可以将期货(与承诺一起)与手动创建的 std::threads 一起使用。使用std::async
是一种为某些异步计算触发线程并通过未来将结果编组回的便捷方法,但std::async
在当前标准中相当有限。如果建议的包含来自 Microsoft 的 PPL 的一些想法的扩展被接受,它将变得更加有用。
Currently, std::async
is probably best suited to handling either very long running computations or long running IO for fairly simple programs. It doesn't guarantee low overhead though (and in fact the way it is specified makes it difficult to implement with a thread pool behind the scenes), so it's not well suited for finer grained workloads. For that you either need to roll your own thread pools using std::thread
or use something like Microsoft's PPL or Intel's TBB.
目前,std::async
对于相当简单的程序,它可能最适合处理非常长时间运行的计算或长时间运行的 IO。但它并不能保证低开销(事实上,它的指定方式使得很难在后台使用线程池实现),因此它不太适合细粒度的工作负载。为此,您需要使用std::thread
或使用 Microsoft 的 PPL 或 Intel 的 TBB 之类的东西来滚动自己的线程池。
You can also use std::thread
for 'traditional' POSIX thread style code written in a more modern and portable way.
您还可以使用std::thread
以更现代和可移植的方式编写的“传统”POSIX 线程样式代码。
Bartosz Milewski discusses some of the limitations of the way std::async
is currently specified in his article Async Tasks in C++11: Not Quite There Yet
Bartosz Milewski 讨论了std::async
当前在他的文章Async Tasks in C++11 中指定的方式的一些限制:尚未完全到位
回答by Robert
One simple reason I've found is the case when you want a way to detect (via polling) whether an asynchronous job is done. With std::thread
, you have to manage it yourself. With std::async
you can query std::future::valid()
(or use std::future::wait_for/wait_until(...)
) to know when it is done.
我发现的一个简单原因是,您需要一种方法来检测(通过轮询)异步作业是否已完成。使用std::thread
,您必须自己管理它。随着std::async
您可以查询std::future::valid()
(或使用std::future::wait_for/wait_until(...)
),当它完成就知道了。