nndeploy C++ API  0.2.0
nndeploy C++ API
thread_pool.h
Go to the documentation of this file.
1 
2 #ifndef _NNDEPLOY_THREAD_POOL_THREAD_POOL_H_
3 #define _NNDEPLOY_THREAD_POOL_THREAD_POOL_H_
4 
5 #include <atomic>
6 #include <future>
7 #include <thread>
8 
9 #include "nndeploy/base/status.h"
13 
14 namespace nndeploy {
15 namespace thread_pool {
17  public:
18  explicit ThreadPool(int size = 4) { max_thread_size_ = size; }
19 
21  for (int i = 0; i < max_thread_size_; i++) {
22  auto ptr = new LocalThread(); // 创建核心线程数
23  ptr->setThreadPoolInfo(i, &threads_, max_thread_size_);
24  // ptr->init();
25  threads_.emplace_back(ptr);
26  }
27  for (int i = 0; i < max_thread_size_; i++) {
28  threads_[i]->init();
29  }
30 
31  return base::Status();
32  }
33 
35  for (auto &pt : threads_) {
36  if (pt) {
37  pt->destroy();
38  }
39  }
40  for (auto &pt : threads_) {
41  if (pt) {
42  delete pt;
43  pt = nullptr;
44  }
45  }
46  threads_.clear();
47 
48  return base::Status();
49  }
50 
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());
57 
58  cur_index_++;
59  if (cur_index_ >= max_thread_size_ || cur_index_ < 0) {
60  cur_index_ = 0;
61  }
62  threads_[cur_index_]->pushTask(std::move(task));
63  return result;
64  }
65 
66  template <typename F>
67  auto commit_to(int slot, F &&f) -> std::future<std::invoke_result_t<F>> {
68  using R = std::invoke_result_t<F>;
69 
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(); };
73 
74  int idx = slot % max_thread_size_;
75  if (idx < 0) idx += max_thread_size_;
76 
77  threads_[idx]->pushTask(std::move(void_task));
78  return fut;
79  }
80 
81  private:
82  std::atomic<int> cur_index_{0};
83  int max_thread_size_ = 0;
84  std::vector<LocalThread *> threads_;
85 };
86 
87 } // namespace thread_pool
88 } // namespace nndeploy
89 
90 // demo
91 // int main(int argc, char *argv[]) {
92 // nndeploy::thread_pool::ThreadPool pool(4);
93 // pool.init();
94 
95 // auto func = [](int a, int b) { return a + b; };
96 // auto result1 = pool.commit(std::bind(func, 1, 2));
97 // std::cout << result1.get() << std::endl;
98 
99 // int i = 0;
100 // int j = 0;
101 // auto result2 = pool.commit([i, j] {
102 // return add(i, j); }));
103 // std::cout << result2.get() << std::endl;
104 
105 // pool.destroy();
106 // return 0;
107 // }
108 
109 #endif //_NNDEPLOY_THREAD_POOL_THREAD_POOL_H_
auto commit_to(int slot, F &&f) -> std::future< std::invoke_result_t< F >>
Definition: thread_pool.h:67
auto commit(const FunctionType &func) -> std::future< decltype(std::declval< FunctionType >()())>
Definition: thread_pool.h:52
#define NNDEPLOY_CC_API
api
Definition: macro.h:29