std :: async的问题是什么? [英] What is the issue with std::async?

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

问题描述

靠近 this clip from C ++ And Beyond,我听说了有关 std :: async 的问题。我有两个问题:

Near the beginning of this clip from C++ And Beyond, I heard something about problems with std::async. I have two questions:


  1. 对于一个初级开发者来说,是有一套规则来做什么和避免什么使用 std :: async

它们与本文相关吗?


推荐答案

有几个问题:


  1. std :: async 没有启动策略允许运行时库选择是启动新线程还是运行任务未来的线程调用 get() wait()。正如Herb说的,这是你最可能想使用的情况。问题是,这使它对运行时库的QoI打开以获得正确的线程数,你不知道任务是否会有一个线程本身,所以使用线程局部变量可能有问题。

  1. std::async without a launch policy lets the runtime library choose whether to start a new thread or run the task in the thread that called get() or wait() on the future. As Herb says, this is the case you most likely want to use. The problem is that this leaves it open to the QoI of the runtime library to get the number of threads right, and you don't know whether the task will have a thread to itself, so using thread-local variables can be problematic. This is what Scott is concerned about, as I understand it.

使用 std :: launch :: deferred的策略

Using a policy of std::launch::deferred doesn't actually run the task until you explicitly call get() or wait(). This is almost never what you want, so don't do that.

使用的策略std :: launch :: async 启动一个新线程。

Using a policy of std::launch::async starts a new thread. If you don't keep track of how many threads you've got, this can lead to too many threads running.

Herb关心的行为是: std :: future 析构函数,它应该等待任务完成,虽然MSVC2012有一个错误,它不等待。

Herb is concerned about the behaviour of the std::future destructor, which is supposed to wait for the task to complete, though MSVC2012 has a bug in that it doesn't wait.

对于初级开发者,我建议:

For a junior developer, I would suggest:


  • 使用默认启动策略使用 std :: async

  • 确保您明确等待所有的未来。 >
  • 不要在异步任务中使用线程本地存储。

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

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