首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >packaged_task和异步之间的区别是什么

packaged_task和异步之间的区别是什么
EN

Stack Overflow用户
提问于 2013-08-09 17:34:55
回答 1查看 34K关注 0票数 152

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

代码语言:javascript
复制
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';

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

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

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

EN

回答 1

Stack Overflow用户

发布于 2021-11-12 09:03:22

TL;DR

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

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

实际例子

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

假设你想实现一个线程池。它由固定数量的工作线程和一个共享队列组成。但是共享队列是什么呢?std::packaged_task在这里非常适合。

代码语言:javascript
复制
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()中执行callable。请注意,您不能为同一共享状态创建多个期货(期货是不可复制的)。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18143661

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档