我正在尝试深入探索新 C++11 标准的所有选项,同时使用 std::async 并阅读其定义,我注意到两件事,至少在带有 gcc 4.8.1 的 linux 下:
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 :
pthread
,如果你想使用 std::async
你需要线程.pthread
, if you want to use std::async
you need pthread.在这一点上,我很自然地问为什么选择 std::async 而不是一组简单的函子?这是一个根本无法扩展的解决方案,您调用的未来越多,您的程序响应就越慢.
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.
另请注意,std::async
可以通过策略 std::launch::async
或 std::launch::deferred
启动>.如果不指定,则允许实现选择,并且很可能选择使用延迟求值,这会导致当您尝试从未来获取结果时,所有工作都已完成,从而导致更长的块.因此,如果您想确保异步完成工作,请使用 std::launch::async
.
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!