When to use promise over async or packaged_task?

后端 未结 2 1323
星月不相逢
星月不相逢 2020-12-22 22:34

When should I use std::promise over std::async or std::packaged_task? Can you give me practical examples of when to use each one of th

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-22 22:53

    A promise is used to store a value that was calculated using e.g. a std::async. See http://en.cppreference.com/w/cpp/thread/promise

    I can imagine you wonder about the difference between std::packaged_task and std::async (in the most common approach, std::async starts a separate thread NOW to run function/lambda/etc with a (likely) expensive calculation. A std::packaged_task is used to wrap a function/lambda/etc with the current values of arguments so you can LATER run it, either synchronously or in a separate thread).

    Both std::packaged_task and std::async provide a std::future that will contain the RESULT of the wrapped function/lambda/etc once run. Internally, the std::future uses a std::promise to hold that result.

提交回复
热议问题