在实现线程池上个版本中,提交任务需要重写Task run 方法,获取结果会被阻塞直至任务完成,使用C++ 异步新标准解决上述问题;
提交任务期望有如下简洁格式:
auto res1 = pool.submitTask(func, 1, 2);
可以使用C++17 模板可变参数:
template<typename Func, typename... Args>
auto submitTask(Func &&func, Args &&...args) /*-> std::future<decltype(func(args...))> */{
using Rtype = decltype(func(args...));
auto task = std::make_shared<std::packaged_task<Rtype()>>(
std::bind(std::forward<Func>(func), std::forward<Args>(args)...));
std::future<Rtype> result = task->get_future();
std::unique_lock<std::mutex> lock(taskQueMtx_);
if (!notFull_.wait_for(lock, std::chrono::seconds(1),
[&]() -> bool { return taskQue_.size() < taskQueMaxThreshHold_; })) {
std::cerr << "task queue is full, submitTask failed.\n";
auto task = std::make_shared<std::packaged_task<Rtype()>>([]() { return Rtype(); });
(*task)();
return task->get_future();
}
taskQue_.emplace([=]() {
(*task)();
});
// ...
}
package_task 和 function 很相近,可以理解为支持异步机制的function;
由于传递的参数为万能引用,std::forward 完美转发从而不改变语义;
异步提交任务后,可以用wait() 等待任务执行完成,get() 获取结果;
std::future<Rtype> result = task->get_future();
result.wait();
result.get();