Skip to content

Commit 41355c0

Browse files
committed
Pass task by universal reference and variadics
As suggested by daniel-j-h tasks are now taken by universal reference and forwarded with std::forward. Also enqueue takes a variadic argument list and binds the arguments to the task.
1 parent 5d0ca72 commit 41355c0

2 files changed

Lines changed: 9 additions & 7 deletions

File tree

ThreadPool.h

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ class Worker {
2626
class ThreadPool {
2727
public:
2828
ThreadPool(size_t);
29-
template<class T, class F>
30-
std::future<T> enqueue(F f);
29+
template<class F, class... Args>
30+
auto enqueue(F&& f, Args&&... args) -> std::future<decltype(std::forward<F>(f)(std::forward<Args>(args)...))>;
3131
~ThreadPool();
3232
private:
3333
friend class Worker;
@@ -68,15 +68,17 @@ ThreadPool::ThreadPool(size_t threads)
6868
}
6969

7070
// add new work item to the pool
71-
template<class T, class F>
72-
std::future<T> ThreadPool::enqueue(F f)
71+
template<class F, class... Args>
72+
auto ThreadPool::enqueue(F&& f, Args&&... args) -> std::future<decltype(std::forward<F>(f)(std::forward<Args>(args)...))>
7373
{
74+
typedef decltype(std::forward<F>(f)(std::forward<Args>(args)...)) return_type;
75+
7476
// don't allow enqueueing after stopping the pool
7577
if(stop)
7678
throw std::runtime_error("enqueue on stopped ThreadPool");
7779

78-
auto task = std::make_shared< std::packaged_task<T()> >(f);
79-
std::future<T> res = task->get_future();
80+
auto task = std::make_shared< std::packaged_task<return_type()> >(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
81+
std::future<return_type> res = task->get_future();
8082
{
8183
std::unique_lock<std::mutex> lock(queue_mutex);
8284
tasks.push([task](){ (*task)(); });

example.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ int main()
1212

1313
for(int i = 0; i < 8; ++i) {
1414
results.push_back(
15-
pool.enqueue<int>([i] {
15+
pool.enqueue([i] {
1616
std::cout << "hello " << i << std::endl;
1717
std::this_thread::sleep_for(std::chrono::seconds(1));
1818
std::cout << "world " << i << std::endl;

0 commit comments

Comments
 (0)