packaged_task 和 async 有什么区别

新手上路,请多包涵

在使用 C++11 的线程模型时,我注意到

std::packaged_task<int(int,int)> task([](int a, int b) { return a + b; });
auto f = task.get_future();
task(2,3);
std::cout << f.get() << '\n';

auto f = std::async(std::launch::async,
    [](int a, int b) { return a + b; }, 2, 3);
std::cout << f.get() << '\n';

似乎做同样的事情。我知道如果我运行 std::asyncstd::launch::deferred 可能会有很大的不同,但是在这种情况下有一个吗?

这两种方法有什么区别,更重要的是,在哪些用例中我应该使用其中一种方法?

原文由 nikolas 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

实际上,如果您使用相当长的函数,您刚刚给出的示例显示了差异,例如

//! sleeps for one second and returns 1
auto sleep = [](){
    std::this_thread::sleep_for(std::chrono::seconds(1));
    return 1;
};

打包任务

A packaged_task 不会自行启动,您必须调用它:

 std::packaged_task<int()> task(sleep);

auto f = task.get_future();
task(); // invoke the function

// You have to wait until task returns. Since task calls sleep
// you will have to wait at least 1 second.
std::cout << "You can see this after 1 second\n";

// However, f.get() will be available, since task has already finished.
std::cout << f.get() << std::endl;

std::async

另一方面, std::asynclaunch::async 将尝试在不同的线程中运行任务:

 auto f = std::async(std::launch::async, sleep);
std::cout << "You can see this immediately!\n";

// However, the value of the future will be available after sleep has finished
// so f.get() can block up to 1 second.
std::cout << f.get() << "This will be shown after a second!\n";

退税

但在你尝试使用 async 之前,请记住返回的未来有一个特殊的共享状态,它要求 future::~future 块:

 std::async(do_work1); // ~future blocks
std::async(do_work2); // ~future blocks

/* output: (assuming that do_work* log their progress)
    do_work1() started;
    do_work1() stopped;
    do_work2() started;
    do_work2() stopped;
*/

因此,如果您想要真正的异步,则需要保留返回的 future ,或者如果情况发生变化您不关心结果:

 {
    auto pizza = std::async(get_pizza);
    /* ... */
    if(need_to_go)
        return;          // ~future will block
    else
       eat(pizza.get());
}

For more information on this, see Herb Sutter’s article async and ~future , which describes the problem, and Scott Meyer’s std::futures from std::async aren ’t special ,它描述了洞察力。另请注意,此行为 是在 C++14 及更高版本中指定的,但也通常在 C++11 中实现。

进一步的差异

通过使用 std::async 您不能再在特定线程上运行您的任务,其中 std::packaged_task 可以移动到其他线程。

 std::packaged_task<int(int,int)> task(...);
auto f = task.get_future();
std::thread myThread(std::move(task),2,3);

std::cout << f.get() << "\n";

此外,在调用 packaged_task 之前需要调用 f.get() ,否则您的程序将冻结,因为未来永远不会准备好:

 std::packaged_task<int(int,int)> task(...);
auto f = task.get_future();
std::cout << f.get() << "\n"; // oops!
task(2,3);

TL;博士

使用 std::async 如果您想要完成某些事情并且并不真正关心它们何时完成,使用 std::packaged_task 如果您想结束事情以便将它们移动到其他线程或稍后打电话给他们。或者,引用 Christian 的话:

最后 std::packaged_task 只是实现 std::async 的较低级别功能(这就是为什么它可以做更多 std::async 如果与其他较低级别的东西一起使用,例如 std::thread )。 Simply spoken a std::packaged_task is a std::function linked to a std::future and std::async wraps and calls a std::packaged_task (possibly在不同的线程中)。

原文由 Zeta 发布,翻译遵循 CC BY-SA 4.0 许可协议

TL;博士

std::packaged_task 允许我们将 std::future “绑定”到某个 callable ,然后控制何时何地执行这个 callable 而不需要那个未来的对象。

std::async 启用第一个,但不启用第二个。也就是说,它允许我们获得一些可调用的未来,但是如果没有这个未来对象,我们就无法控制它的执行。

实际例子

这是一个可以用 std::packaged_task 但不能用 std::async 解决的问题的实际示例。

考虑你想实现一个 _线程池_。它由固定数量的 工作线程 和一个 共享队列 组成。但是共享队列是什么? std::packaged_task 这里很适合。

 template <typename T>
class ThreadPool {
public:
  using task_type = std::packaged_task<T()>;

  std::future<T> enqueue(task_type task) {
      // could be passed by reference as well...
      // ...or implemented with perfect forwarding
    std::future<T> res = task.get_future();
    { std::lock_guard<std::mutex> lock(mutex_);
      tasks_.push(std::move(task));
    }
    cv_.notify_one();
    return res;
  }

  void worker() {
    while (true) {  // supposed to be run forever for simplicity
      task_type task;
      { std::unique_lock<std::mutex> lock(mutex_);
        cv_.wait(lock, [this]{ return !this->tasks_.empty(); });
        task = std::move(tasks_.top());
        tasks_.pop();
      }
      task();
    }
  }
  ... // constructors, destructor,...
private:
  std::vector<std::thread> workers_;
  std::queue<task_type> tasks_;
  std::mutex mutex_;
  std::condition_variable cv_;
};

这样的功能不能用 std::async 实现。我们需要从 enqueue() 返回一个 std::future 。如果我们在那里调用 std::async (即使使用 延迟 策略)并返回 std::future ,那么我们将无法选择如何在 worker() 中执行调用请注意,您不能为同一个共享状态创建多个期货(期货是不可复制的)。

原文由 Daniel Langr 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题