Skip to content

Commit 4a55bec

Browse files
committed
Refactored thread pool executor with type erasure to allow tasks with different types (#415)
1 parent dcf4d59 commit 4a55bec

File tree

2 files changed

+8
-6
lines changed

2 files changed

+8
-6
lines changed

src/util/thread_pool_executor.cc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ void thread_pool_executor::worker()
5555
}
5656
}
5757

58-
std::packaged_task<void()> thread_pool_executor::get()
58+
std::function<void()> thread_pool_executor::get()
5959
{
6060
std::unique_lock<std::mutex> l(tasks_mutex_);
6161

src/util/thread_pool_executor.h

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
#pragma once
1919

2020
#include <deque>
21+
#include <functional>
2122
#include <future>
2223
#include <thread>
2324
#include <vector>
@@ -53,10 +54,11 @@ class thread_pool_executor {
5354
{
5455
std::unique_lock<std::mutex> l(tasks_mutex_);
5556

56-
std::packaged_task<T()> ptask{std::forward<F>(task)};
57-
auto res = ptask.get_future();
57+
auto ptask =
58+
std::make_shared<std::packaged_task<T()>>(std::forward<F>(task));
59+
auto res = ptask->get_future();
5860

59-
tasks_.emplace_back(std::move(ptask));
61+
tasks_.emplace_back([ptask = std::move(ptask)]() { (*ptask)(); });
6062

6163
l.unlock();
6264
tasks_cond_.notify_one();
@@ -75,10 +77,10 @@ class thread_pool_executor {
7577
*/
7678
void worker();
7779

78-
std::packaged_task<void()> get();
80+
std::function<void()> get();
7981

8082
std::atomic_bool done_;
81-
std::deque<std::packaged_task<void()>> tasks_;
83+
std::deque<std::function<void()>> tasks_;
8284
std::mutex tasks_mutex_;
8385
std::condition_variable tasks_cond_;
8486
std::vector<std::thread> threads_;

0 commit comments

Comments
 (0)