hthreadpool.h 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. #ifndef HV_THREAD_POOL_H_
  2. #define HV_THREAD_POOL_H_
  3. /*
  4. * @usage unittest/threadpool_test.cpp
  5. */
  6. #include <time.h>
  7. #include <thread>
  8. #include <list>
  9. #include <queue>
  10. #include <functional>
  11. #include <atomic>
  12. #include <mutex>
  13. #include <condition_variable>
  14. #include <future>
  15. #include <memory>
  16. #include <utility>
  17. #include <chrono>
  18. #define DEFAULT_THREAD_POOL_MIN_THREAD_NUM 1
  19. #define DEFAULT_THREAD_POOL_MAX_THREAD_NUM std::thread::hardware_concurrency()
  20. #define DEFAULT_THREAD_POOL_MAX_IDLE_TIME 60000 // ms
  21. class HThreadPool {
  22. public:
  23. using Task = std::function<void()>;
  24. HThreadPool(int min_threads = DEFAULT_THREAD_POOL_MIN_THREAD_NUM,
  25. int max_threads = DEFAULT_THREAD_POOL_MAX_THREAD_NUM,
  26. int max_idle_ms = DEFAULT_THREAD_POOL_MAX_IDLE_TIME)
  27. : min_thread_num(min_threads)
  28. , max_thread_num(max_threads)
  29. , max_idle_time(max_idle_ms)
  30. , status(STOP)
  31. , cur_thread_num(0)
  32. , idle_thread_num(0)
  33. {}
  34. virtual ~HThreadPool() {
  35. stop();
  36. }
  37. void setMinThreadNum(int min_threads) {
  38. min_thread_num = min_threads;
  39. }
  40. void setMaxThreadNum(int max_threads) {
  41. max_thread_num = max_threads;
  42. }
  43. void setMaxIdleTime(int ms) {
  44. max_idle_time = ms;
  45. }
  46. int currentThreadNum() {
  47. return cur_thread_num;
  48. }
  49. int idleThreadNum() {
  50. return idle_thread_num;
  51. }
  52. size_t taskNum() {
  53. std::lock_guard<std::mutex> locker(task_mutex);
  54. return tasks.size();
  55. }
  56. bool isStarted() {
  57. return status != STOP;
  58. }
  59. bool isStopped() {
  60. return status == STOP;
  61. }
  62. int start(int start_threads = 0) {
  63. if (status != STOP) return -1;
  64. status = RUNNING;
  65. if (start_threads < min_thread_num) start_threads = min_thread_num;
  66. if (start_threads > max_thread_num) start_threads = max_thread_num;
  67. for (int i = 0; i < start_threads; ++i) {
  68. createThread();
  69. }
  70. return 0;
  71. }
  72. int stop() {
  73. if (status == STOP) return -1;
  74. status = STOP;
  75. task_cond.notify_all();
  76. for (auto& i : threads) {
  77. if (i.thread->joinable()) {
  78. i.thread->join();
  79. }
  80. }
  81. threads.clear();
  82. cur_thread_num = 0;
  83. idle_thread_num = 0;
  84. return 0;
  85. }
  86. int pause() {
  87. if (status == RUNNING) {
  88. status = PAUSE;
  89. }
  90. return 0;
  91. }
  92. int resume() {
  93. if (status == PAUSE) {
  94. status = RUNNING;
  95. }
  96. return 0;
  97. }
  98. int wait() {
  99. while (status != STOP) {
  100. if (tasks.empty() && idle_thread_num == cur_thread_num) {
  101. break;
  102. }
  103. std::this_thread::yield();
  104. }
  105. return 0;
  106. }
  107. /*
  108. * return a future, calling future.get() will wait task done and return RetType.
  109. * commit(fn, args...)
  110. * commit(std::bind(&Class::mem_fn, &obj))
  111. * commit(std::mem_fn(&Class::mem_fn, &obj))
  112. *
  113. */
  114. template<class Fn, class... Args>
  115. auto commit(Fn&& fn, Args&&... args) -> std::future<decltype(fn(args...))> {
  116. if (status == STOP) start();
  117. if (idle_thread_num <= tasks.size() && cur_thread_num < max_thread_num) {
  118. createThread();
  119. }
  120. using RetType = decltype(fn(args...));
  121. auto task = std::make_shared<std::packaged_task<RetType()> >(
  122. std::bind(std::forward<Fn>(fn), std::forward<Args>(args)...));
  123. std::future<RetType> future = task->get_future();
  124. {
  125. std::lock_guard<std::mutex> locker(task_mutex);
  126. tasks.emplace([task]{
  127. (*task)();
  128. });
  129. }
  130. task_cond.notify_one();
  131. return future;
  132. }
  133. protected:
  134. bool createThread() {
  135. if (cur_thread_num >= max_thread_num) return false;
  136. std::thread* thread = new std::thread([this] {
  137. while (status != STOP) {
  138. while (status == PAUSE) {
  139. std::this_thread::yield();
  140. }
  141. Task task;
  142. {
  143. std::unique_lock<std::mutex> locker(task_mutex);
  144. task_cond.wait_for(locker, std::chrono::milliseconds(max_idle_time), [this]() {
  145. return status == STOP || !tasks.empty();
  146. });
  147. if (status == STOP) return;
  148. if (tasks.empty()) {
  149. if (cur_thread_num > min_thread_num) {
  150. delThread(std::this_thread::get_id());
  151. return;
  152. }
  153. continue;
  154. }
  155. --idle_thread_num;
  156. task = std::move(tasks.front());
  157. tasks.pop();
  158. }
  159. if (task) {
  160. task();
  161. ++idle_thread_num;
  162. }
  163. }
  164. });
  165. addThread(thread);
  166. return true;
  167. }
  168. void addThread(std::thread* thread) {
  169. thread_mutex.lock();
  170. ++cur_thread_num;
  171. ++idle_thread_num;
  172. ThreadData data;
  173. data.thread = std::shared_ptr<std::thread>(thread);
  174. data.id = thread->get_id();
  175. data.status = RUNNING;
  176. data.start_time = time(NULL);
  177. data.stop_time = 0;
  178. threads.emplace_back(data);
  179. thread_mutex.unlock();
  180. }
  181. void delThread(std::thread::id id) {
  182. time_t now = time(NULL);
  183. thread_mutex.lock();
  184. --cur_thread_num;
  185. --idle_thread_num;
  186. auto iter = threads.begin();
  187. while (iter != threads.end()) {
  188. if (iter->status == STOP && now > iter->stop_time) {
  189. if (iter->thread->joinable()) {
  190. iter->thread->join();
  191. iter = threads.erase(iter);
  192. continue;
  193. }
  194. } else if (iter->id == id) {
  195. iter->status = STOP;
  196. iter->stop_time = time(NULL);
  197. }
  198. ++iter;
  199. }
  200. thread_mutex.unlock();
  201. }
  202. public:
  203. int min_thread_num;
  204. int max_thread_num;
  205. int max_idle_time;
  206. protected:
  207. enum Status {
  208. STOP,
  209. RUNNING,
  210. PAUSE,
  211. };
  212. struct ThreadData {
  213. std::shared_ptr<std::thread> thread;
  214. std::thread::id id;
  215. Status status;
  216. time_t start_time;
  217. time_t stop_time;
  218. };
  219. std::atomic<Status> status;
  220. std::atomic<int> cur_thread_num;
  221. std::atomic<int> idle_thread_num;
  222. std::list<ThreadData> threads;
  223. std::mutex thread_mutex;
  224. std::queue<Task> tasks;
  225. std::mutex task_mutex;
  226. std::condition_variable task_cond;
  227. };
  228. #endif // HV_THREAD_POOL_H_