为什么要使用 std::async?

Why should I use std::async?(为什么要使用 std::async?)

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

问题描述

我正在尝试深入探索新 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 :

  • 它被称为async,但它有一个真正的顺序行为",基本上在你调用与你的异步函数foo<相关的未来的那一行/em>,程序会阻塞,直到 foo 执行完成.
  • 它依赖于与其他完全相同的外部库,以及更好的非阻塞解决方案,这意味着 pthread,如果你想使用 std::async 你需要线程.
  • 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.

在这一点上,我很自然地问为什么选择 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::asyncstd::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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:为什么要使用 std::async?

基础教程推荐