gpt4 book ai didi

c++ - 为什么我应该使用 std::async?

转载 作者:IT老高 更新时间:2023-10-28 13:20:45 29 4
gpt4 key购买 nike

我正在尝试深入探索新 C++11 标准的所有选项,在使用 std::async 并阅读其定义时,我注意到两件事,至少在 linux 下使用 gcc 4.8.1 :

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

在这一点上,我很自然地问为什么选择 std::async 而不是一组简单的仿函数?这是一个根本无法扩展的解决方案,您调用的 future 越多,您的程序响应速度就越慢。

我错过了什么吗?您能否展示一个允许以异步、非阻塞方式执行的示例?

最佳答案

  • it's called async, but it got a really "sequential behaviour",

不,如果您使用 std::launch::async 策略,那么它会在新线程中异步运行。如果您不指定策略,它可能在新线程中运行。

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.

它仅在 foo 未完成时阻塞,但如果它是异步运行的(例如,因为您使用 std::launch::async 策略)它可能在您需要它之前已经完成。

  • 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.

错了,它不必使用 Pthreads 来实现(在 Windows 上不是,它使用 ConcRT 功能。)

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.

不一定。如果您没有指定启动策略,那么智能实现可以决定是启动一个新线程,还是返回一个延迟函数,或者返回一些稍后决定的东西,当更多资源可用时。

现在,确实,对于 GCC 的实现,如果您不提供启动策略,那么在当前版本中它永远不会在新线程中运行(有一个 bugzilla report),但这是该实现的一个属性,通常不是 std::async 。您不应将标准中的规范与特定实现混淆。阅读一个标准库的实现是了解 C++11 的一种糟糕方式。

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

这不应该阻止:

auto fut = std::async(std::launch::async, doSomethingThatTakesTenSeconds);
auto result1 = doSomethingThatTakesTwentySeconds();
auto result2 = fut.get();

通过指定启动策略,您可以强制异步执行,如果您在执行时执行其他工作,那么结果将在您需要时准备就绪。

关于c++ - 为什么我应该使用 std::async?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17963172/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com