何时使用std :: async与std :: threads? [英] When to use std::async vs std::threads?

查看:97
本文介绍了何时使用std :: async与std :: threads?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以对何时使用它们有个高度的直觉吗?

Can anybody give a high level intuition about when to use each of them?

参考文献:

  • Is it smart to replace boost::thread and boost::mutex with c++11 equivalents?
  • When is it a good idea to use std::promise over the other std::thread mechanisms?

推荐答案

这实际上不是的东西-您可以将Future(与promise一起)与手动创建的std :: threads一起使用.使用std::async是触发线程进行某些异步计算并通过将来将其封送回结果的一种便捷方法,但是std::async在当前标准中受到很大限制.如果接受建议的扩展以合并Microsoft PPL的一些想法,它将变得更加有用.

It's not really an either-or thing - 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::async可能最适合处理相当简单的程序的非常长时间运行的计算或长时间运行的IO.但是,它不能保证较低的开销(实际上,它的指定方式使幕后线程池难以实现),因此它不太适合粒度更细的工作负载.为此,您需要使用std::thread滚动自己的线程池,或者使用类似Microsoft的PPL或Intel的TBB之类的东西.

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::thread用于以更现代,更可移植的方式编写的传统" POSIX线程样式代码.

You can also use std::thread for 'traditional' POSIX thread style code written in a more modern and portable way.

Bartosz Milewski在其文章 C ++ 11中的异步任务:还没有

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

这篇关于何时使用std :: async与std :: threads?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆