2 #ifndef _NNDEPLOY_THREAD_POOL_THREAD_POOL_H_
3 #define _NNDEPLOY_THREAD_POOL_THREAD_POOL_H_
15 namespace thread_pool {
18 explicit ThreadPool(
int size = 4) { max_thread_size_ = size; }
21 for (
int i = 0; i < max_thread_size_; i++) {
23 ptr->setThreadPoolInfo(i, &threads_, max_thread_size_);
25 threads_.emplace_back(ptr);
27 for (
int i = 0; i < max_thread_size_; i++) {
35 for (
auto &pt : threads_) {
40 for (
auto &pt : threads_) {
51 template <
typename FunctionType>
52 auto commit(
const FunctionType &func)
53 -> std::future<decltype(std::declval<FunctionType>()())> {
54 using ResultType = decltype(std::declval<FunctionType>()());
55 std::packaged_task<ResultType()> task(func);
56 std::future<ResultType> result(task.get_future());
59 if (cur_index_ >= max_thread_size_ || cur_index_ < 0) {
62 threads_[cur_index_]->pushTask(std::move(task));
67 auto commit_to(
int slot, F &&f) -> std::future<std::invoke_result_t<F>> {
68 using R = std::invoke_result_t<F>;
70 std::packaged_task<R()> pt(std::forward<F>(f));
71 auto fut = pt.get_future();
72 auto void_task = [task = std::move(pt)]()
mutable { task(); };
74 int idx = slot % max_thread_size_;
75 if (idx < 0) idx += max_thread_size_;
77 threads_[idx]->pushTask(std::move(void_task));
82 std::atomic<int> cur_index_{0};
83 int max_thread_size_ = 0;
84 std::vector<LocalThread *> threads_;
auto commit_to(int slot, F &&f) -> std::future< std::invoke_result_t< F >>
auto commit(const FunctionType &func) -> std::future< decltype(std::declval< FunctionType >()())>
#define NNDEPLOY_CC_API
api