Reputation: 2541
here and here , we can see similar threadpool implementations.
my question is about function to add the task to threadpool, these are add and enqueue in projects above respectively.
because these look very similar I'm posting a piece of one here (from second project)
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;
}
container tasks declared as :
std::queue< std::function<void()> > tasks;
so my questions are:
Upvotes: 6
Views: 461
Reputation: 2868
In case you are still looking for an answer (you mostly answered it on your own):
Current HPC thread pool implementations mostly use a work stealing scheduler: Each worker has its own queue. The worker pulls and pushes work from/to his own queue, until he has finished all the tasks in its own queue. Then it steals tasks from other workers and executes those.
Upvotes: 2