In C 17, I find no executor other than just creating a std::thread
to execute a std::packed_task
and then fetch its result.
I found some demos of executors for std::packed_task
. However this is just a demo without any optimization.
However, I wonder if there are some mature implementation of thread pool that can execute a std::packed_task
?
CodePudding user response:
According to @Pepijn Kramer's comment, I have the following implementation.
#include "thread_pool.h"
#include <future>
#include <memory>
#include <chrono>
int main() {
using namespace std::chrono_literals;
int total = 10;
int thread_size = 4;
// From thread_pool.h
Nuke::ThreadExecutor pool(thread_size);
std::vector<std::future<int>> futs;
for (int i = 0; i < total; i ) {
using P = std::packaged_task<int()>;
std::shared_ptr<P> task = std::make_shared<P>([i]() {
std::this_thread::sleep_for(1000ms);
return i;
});
futs.emplace_back(task->get_future());
pool.add_task([task]() { (*task)(); });
}
for (int i = 0; i < total; i ) {
printf("%d\n", futs[i].get());
}
}
I used my implementation of a task queue, which only handles std::function<void()>
.
By wrapping my std::packaged_task<int()>
into std::function<void()>
, I can reuse my task queue.