Medium
std::packaged_task in a thread pool's submit()
A thread pool's submit() function needs to hand work to whichever worker thread picks it up next from a shared queue, while still giving the caller a std::future for the result. Why is std::packaged_task used here instead of just calling std::async(f) directly?
main.cpp
std::queue<std::packaged_task<int()>> taskQueue;
std::mutex qmtx;
std::condition_variable qcv;
std::future<int> submit(std::function<int()> job) {
std::packaged_task<int()> task(std::move(job));
std::future<int> fut = task.get_future();
{
std::lock_guard<std::mutex> lock(qmtx);
taskQueue.push(std::move(task));
}
qcv.notify_one();
return fut;
}
// worker thread loop:
// std::packaged_task<int()> t = std::move(taskQueue.front()); taskQueue.pop();
// t(); // runs job(), fulfills fut automatically via its shared state30 of 51 in Concurrency