在使用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::launch::deferred
运行std::async
可能会有很大的不同,但是在这种情况下有吗?
这两种方法有什么区别,更重要的是,我应该在哪些用例中使用一种方法而不是另一种方法?
发布于 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
在这里非常适合。
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。请注意,您不能为同一共享状态创建多个期货(期货是不可复制的)。
https://stackoverflow.com/questions/18143661
复制相似问题