threadpool.hh 1.61 KB
Newer Older
1
2
3
4
5
#ifndef RADIX_RADIXPARA_THREAD_POOL_HH_
#define RADIX_RADIXPARA_THREAD_POOL_HH_

#include <condition_variable>
#include <functional>
6
#include <future>
7
8
#include <memory>
#include <mutex>
9
#include <queue>
10
11
12
13
#include <stdexcept>
#include <thread>
#include <vector>

14
#include "radixcore/visibility.hh"
15

16
17
18
19
namespace radix
{
class RADIX_PUBLIC ThreadPool
{
20
21
 public:
  typedef std::unique_lock<std::mutex> ThreadLock;
22

23
24
25
26
27
28
29
30
31
32
  /**
   * @brief ThreadPool default constructs with hardware_concurrency
   */
  ThreadPool();
  /**
   * @brief ThreadPool constructs ThreadPool with some number of threads
   * @param numThreads size_t number of threads
   */
  explicit ThreadPool(size_t numThreads);
  ~ThreadPool();
33

34
35
36
37
38
39
40
41
  template <class FunctionType, class... ArgumentList>
  std::future<typename std::result_of<FunctionType(ArgumentList...)>::type>
  queue(FunctionType &&func, ArgumentList &&... args);
  /**
   * @brief threads retrieve const reference to list of threads
   * @return const std::vector<std::thread>&
   */
  const std::vector<std::thread> &threads() const { return mWorkers; }
42

43
44
45
 private:
  // initializes with number of threads
  void init(size_t numThreads);
46

47
48
  // need to keep track of threads so we can join them
  std::vector<std::thread> mWorkers;
49

50
51
  // the task queue
  std::queue<std::function<void()>> mTasks;
52

53
54
  // synchronization for the task queue
  std::mutex mQueueMutex;
55

56
57
  // thread conditional
  std::condition_variable mCondition;
58

59
60
61
  // thread pool halt
  bool mStop;
};  // class ThreadPool
62

63
}  // namespace radix
64
65
66
67
68

// Include template implementation
#include "radixpara/threadpool.i.hh"

#endif /** RADIX_RADIXPARA_THREAD_POOL_HH_ */