I want to create a thread pool for experimental purposes (and for the fun factor). It should be able to process a wide variety of tasks (so I can possibly use it in later projects).
In my thread pool class I'm going to need some sort of task queue. Since the Standard Library provides std::packaged_task
since the C++11 standard, my queue will look like std::deque<std::packaged_task<?()> > task_queue
, so the client can push std::packaged_task
s into the queue via some sort of public interface function (and then one of the threads in the pool will be notified with a condition variable to execute it, etc.).
My question is related to the template argument of the std::packaged_task<?()>
s in the deque.
The function signature ?()
should be able to deal with any type/number of parameters, because the client can do something like:
std::packaged_task<int()> t(std::bind(factorial, 342));
thread_pool.add_task(t);
So I don't have to deal with the type/number of parameters.
But what should the return value be? (hence the question mark)
If I make my whole thread pool class a template class, one instance of it will only be able to deal with tasks with a specific signature (like
std::packaged_task<int()>
).I want one thread pool object to be able to deal with any kind of task.
If I go with
std::packaged_task<void()>
and the function invoked returns an integer, or anything at all, then thats undefined behaviour.
std::deque<std::function<void()>>
, a list of callables that will wake up threads, run tasks and so on. I think that somewhat more interesting question is where and when are you going to retrieve the result of the task? You can return a future or expect callbacks, for example. – Leicestershirepackaged_task
does, and the OP is already using it. – Planosporestd::function
. Args should be bound using a lambda or helper prior to entering the queue. Retval populates afuture
.packaged_task()
returnsvoid
.condition_variable
s for wake up workers.std::future
orstd::thread
for worker thread lifetimes. – Sheepdipthread pool
butscheduler
– Hyperploid