ThreadPool.h 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. /*
  2. * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  3. *
  4. * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
  5. *
  6. * Use of this source code is governed by MIT license that can be found in the
  7. * LICENSE file in the root of the source tree. All contributing project authors
  8. * may be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef THREADPOOL_H_
  11. #define THREADPOOL_H_
  12. #include "threadgroup.h"
  13. #include "TaskQueue.h"
  14. #include "TaskExecutor.h"
  15. #include "Util/util.h"
  16. #include "Util/logger.h"
  17. namespace toolkit {
  18. class ThreadPool : public TaskExecutor {
  19. public:
  20. enum Priority {
  21. PRIORITY_LOWEST = 0,
  22. PRIORITY_LOW,
  23. PRIORITY_NORMAL,
  24. PRIORITY_HIGH,
  25. PRIORITY_HIGHEST
  26. };
  27. ThreadPool(int num = 1, Priority priority = PRIORITY_HIGHEST, bool auto_run = true, bool set_affinity = true,
  28. const std::string &pool_name = "thread pool") {
  29. _thread_num = num;
  30. _on_setup = [pool_name, priority, set_affinity](int index) {
  31. std::string name = pool_name + ' ' + std::to_string(index);
  32. setPriority(priority);
  33. setThreadName(name.data());
  34. if (set_affinity) {
  35. setThreadAffinity(index % std::thread::hardware_concurrency());
  36. }
  37. };
  38. _logger = Logger::Instance().shared_from_this();
  39. if (auto_run) {
  40. start();
  41. }
  42. }
  43. ~ThreadPool() {
  44. shutdown();
  45. wait();
  46. }
  47. //把任务打入线程池并异步执行
  48. Task::Ptr async(TaskIn task, bool may_sync = true) override {
  49. if (may_sync && _thread_group.is_this_thread_in()) {
  50. task();
  51. return nullptr;
  52. }
  53. auto ret = std::make_shared<Task>(std::move(task));
  54. _queue.push_task(ret);
  55. return ret;
  56. }
  57. Task::Ptr async_first(TaskIn task, bool may_sync = true) override {
  58. if (may_sync && _thread_group.is_this_thread_in()) {
  59. task();
  60. return nullptr;
  61. }
  62. auto ret = std::make_shared<Task>(std::move(task));
  63. _queue.push_task_first(ret);
  64. return ret;
  65. }
  66. size_t size() {
  67. return _queue.size();
  68. }
  69. static bool setPriority(Priority priority = PRIORITY_NORMAL, std::thread::native_handle_type threadId = 0) {
  70. // set priority
  71. #if defined(_WIN32)
  72. static int Priorities[] = { THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_HIGHEST };
  73. if (priority != PRIORITY_NORMAL && SetThreadPriority(GetCurrentThread(), Priorities[priority]) == 0) {
  74. return false;
  75. }
  76. return true;
  77. #else
  78. static int Min = sched_get_priority_min(SCHED_OTHER);
  79. if (Min == -1) {
  80. return false;
  81. }
  82. static int Max = sched_get_priority_max(SCHED_OTHER);
  83. if (Max == -1) {
  84. return false;
  85. }
  86. static int Priorities[] = {Min, Min + (Max - Min) / 4, Min + (Max - Min) / 2, Min + (Max - Min) * 3 / 4, Max};
  87. if (threadId == 0) {
  88. threadId = pthread_self();
  89. }
  90. struct sched_param params;
  91. params.sched_priority = Priorities[priority];
  92. return pthread_setschedparam(threadId, SCHED_OTHER, &params) == 0;
  93. #endif
  94. }
  95. void start() {
  96. if (_thread_num <= 0) {
  97. return;
  98. }
  99. size_t total = _thread_num - _thread_group.size();
  100. for (size_t i = 0; i < total; ++i) {
  101. _thread_group.create_thread([this, i]() {run(i);});
  102. }
  103. }
  104. private:
  105. void run(size_t index) {
  106. _on_setup(index);
  107. Task::Ptr task;
  108. while (true) {
  109. startSleep();
  110. if (!_queue.get_task(task)) {
  111. //空任务,退出线程
  112. break;
  113. }
  114. sleepWakeUp();
  115. try {
  116. (*task)();
  117. task = nullptr;
  118. } catch (std::exception &ex) {
  119. ErrorL << "ThreadPool catch a exception: " << ex.what();
  120. }
  121. }
  122. }
  123. void wait() {
  124. _thread_group.join_all();
  125. }
  126. void shutdown() {
  127. _queue.push_exit(_thread_num);
  128. }
  129. private:
  130. size_t _thread_num;
  131. Logger::Ptr _logger;
  132. thread_group _thread_group;
  133. TaskQueue<Task::Ptr> _queue;
  134. std::function<void(int)> _on_setup;
  135. };
  136. } /* namespace toolkit */
  137. #endif /* THREADPOOL_H_ */