为什么要使用std :: async? [英] Why should I use std::async?

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

问题描述

在尝试使用std :: async并阅读其定义的同时,我试图深入探索新C ++ 11标准的所有选项,至少在Linux上使用gcc 4.8.1的情况下,我注意到了两点:/p>

  • 它称为 async ,但它具有真正的顺序行为",基本上是在与异步函数 foo <相关联的 future 所在的行中/em>,程序将阻塞直到 foo 执行完成.
  • 它依赖于与其他库完全相同的外部库以及更好的非阻塞解决方案,这意味着pthread,如果要使用std::async,则需要pthread.

在这一点上,我很自然地问,为什么甚至在一组简单的函子上都选择std :: async?该解决方案甚至根本无法扩展,您调用的未来越多,程序的响应速度就越慢.

我想念什么吗?您能否显示一个示例,该示例被授予以异步,非阻塞方式执行?

解决方案

如果需要异步操作的结果,则必须进行阻止,无论使用哪种库.这样的想法是,您可以选择何时阻止,并且希望在执行此操作时,可以忽略不计的时间,因为所有工作都已经完成.

还请注意,std::async可以与策略std::launch::asyncstd::launch::deferred启动.如果未指定,则允许选择实现,并且它很可能选择使用递延评估,当您尝试从将来获取结果时,这将导致所有工作都已完成,从而导致更长的代码块.因此,如果您要确保工作是异步完成的,请使用std::launch::async.

I'm trying to explore all the options of the new C++11 standard in depth, while using std::async and reading its definition, I noticed 2 things, at least under linux with gcc 4.8.1 :

  • it's called async, but it got a really "sequential behaviour", basically in the row where you call the future associated with your async function foo, the program blocks until the execution of foo it's completed.
  • it depends on the exact same external library as others, and better, non-blocking solutions, which means pthread, if you want to use std::async you need pthread.

at this point it's natural for me asking why choosing std::async over even a simple set of functors ? It's a solution that doesn't even scale at all, the more future you call, the less responsive your program will be.

Am I missing something ? Can you show an example that is granted to be executed in an async, non blocking, way ?

解决方案

If you need the result of an asynchronous operation, then you have to block, no matter what library you use. The idea is that you get to choose when to block, and, hopefully when you do that, you block for a negligible time because all the work has already been done.

Note also that std::async can be launched with policies std::launch::async or std::launch::deferred. If you don't specify it, the implementation is allowed to choose, and it could well choose to use deferred evaluation, which would result in all the work being done when you attempt to get the result from the future, resulting in a longer block. So if you want to make sure that the work is done asynchronously, use std::launch::async.

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

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