1
0

hthreadpool.h 6.6 KB

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