What is the issue with std::async?

后端 未结 2 453
耶瑟儿~
耶瑟儿~ 2020-12-30 02:30

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

  1. For a junior devel

2条回答
  •  长情又很酷
    2020-12-30 03:07

    There are several issues:

    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.

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

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

    4. 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:

    • Use std::async with the default launch policy.
    • Make sure you explicitly wait for all your futures.
    • Don't use thread-local storage in the async tasks.

提交回复
热议问题