我的问题是关于将任务添加到线程池的功能,这些是分别在上面的项目中添加和排队.
因为这些看起来非常相似我在这里张贴了一块(来自第二个项目)
auto ThreadPool::enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>
{
using return_type = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared< std::packaged_task<return_type()> >(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);
// don't allow enqueueing after stopping the pool
if(stop)
throw std::runtime_error("enqueue on stopped ThreadPool");
tasks.emplace([task](){ (*task)(); });
}
condition.notify_one();
return res;
}
Run Code Online (Sandbox Code Playgroud)
容器任务声明为:
std::queue< std::function<void()> > tasks;
Run Code Online (Sandbox Code Playgroud)
所以我的问题是: