Motorcortex Core  version: 2.7.6
ct_threadpool.h
1 /*
2  * Developer : Alexey Zakharov (alexey.zakharov@vectioneer.com)
3  * All rights reserved. Copyright (c) 2020 VECTIONEER.
4  */
5 
6 #ifndef MOTORCORTEX_CORE_CT_THREADPOOL_H
7 #define MOTORCORTEX_CORE_CT_THREADPOOL_H
8 
9 #include "ct_tasksched.h"
10 #include "utl_fncwrapper.h"
11 #include "utl_tsqueue.h"
12 
13 #include <atomic>
14 #include <future>
15 #include <thread>
16 #include <vector>
17 
18 namespace mcx::container {
19 
20 class JoinThreads {
21 public:
22  explicit JoinThreads(std::vector<std::thread>& threads) : threads_(threads) {}
23 
24  ~JoinThreads() {
25  for (auto& thread : threads_) {
26  if (thread.joinable())
27  thread.join();
28  }
29  }
30 
31 private:
32  std::vector<std::thread>& threads_;
33 };
34 
35 class ThreadPool {
36 
37 public:
38  explicit ThreadPool(size_t thread_count = std::thread::hardware_concurrency());
39 
40  ~ThreadPool();
41 
42  bool setName(std::string name);
43 
44  std::string getName() const;
45 
46  bool setTaskSched(TaskSched task_sched, int task_prio = 0);
47 
48  std::tuple<TaskSched, int> getTaskSched() const;
49 
50  bool setCpuAffinity(const std::vector<uint32_t>& cpu_affinity_list);
51 
52  std::vector<uint32_t> getCpuAffinity() const;
53 
54  template <typename FunctionType>
55  std::future<typename std::result_of<FunctionType()>::type> submit(FunctionType f) {
56  typedef typename std::result_of<FunctionType()>::type result_type;
57  std::packaged_task<result_type()> task(std::move(f));
58  std::future<result_type> res(task.get_future());
59  work_queue_.push(std::move(task));
60  return res;
61  }
62 
63  bool empty() const;
64 
65 private:
66  void workerThread();
67 
68  static constexpr size_t MAX_THREAD_NAME_LEN = 16;
69  std::vector<std::thread> threads_;
70  std::vector<std::thread::native_handle_type> ids_;
72  std::atomic_bool done_{};
73  std::atomic_int counter_{};
74  JoinThreads joiner_;
75 };
76 
77 } // namespace mcx::container
78 
79 #endif // MOTORCORTEX_CORE_CT_THREADPOOL_H
ThreadSafeQueue< FunctionWrapper >
mcx::container::ThreadPool
Definition: ct_threadpool.h:35
mcx::container::JoinThreads
Definition: ct_threadpool.h:20