ThreadPool.cpp 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. //==-- llvm/Support/ThreadPool.cpp - A ThreadPool implementation -*- C++ -*-==//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements a crude C++11 based thread pool.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Support/ThreadPool.h"
  13. #include "llvm/Config/llvm-config.h"
  14. #if LLVM_ENABLE_THREADS
  15. #include "llvm/Support/Threading.h"
  16. #else
  17. #include "llvm/Support/raw_ostream.h"
  18. #endif
  19. using namespace llvm;
  20. #if LLVM_ENABLE_THREADS
  21. // A note on thread groups: Tasks are by default in no group (represented
  22. // by nullptr ThreadPoolTaskGroup pointer in the Tasks queue) and functionality
  23. // here normally works on all tasks regardless of their group (functions
  24. // in that case receive nullptr ThreadPoolTaskGroup pointer as argument).
  25. // A task in a group has a pointer to that ThreadPoolTaskGroup in the Tasks
  26. // queue, and functions called to work only on tasks from one group take that
  27. // pointer.
  28. ThreadPool::ThreadPool(ThreadPoolStrategy S)
  29. : Strategy(S), MaxThreadCount(S.compute_thread_count()) {}
  30. void ThreadPool::grow(int requested) {
  31. llvm::sys::ScopedWriter LockGuard(ThreadsLock);
  32. if (Threads.size() >= MaxThreadCount)
  33. return; // Already hit the max thread pool size.
  34. int newThreadCount = std::min<int>(requested, MaxThreadCount);
  35. while (static_cast<int>(Threads.size()) < newThreadCount) {
  36. int ThreadID = Threads.size();
  37. Threads.emplace_back([this, ThreadID] {
  38. Strategy.apply_thread_strategy(ThreadID);
  39. processTasks(nullptr);
  40. });
  41. }
  42. }
  43. #ifndef NDEBUG
  44. // The group of the tasks run by the current thread.
  45. static LLVM_THREAD_LOCAL std::vector<ThreadPoolTaskGroup *>
  46. *CurrentThreadTaskGroups = nullptr;
  47. #endif
  48. // WaitingForGroup == nullptr means all tasks regardless of their group.
  49. void ThreadPool::processTasks(ThreadPoolTaskGroup *WaitingForGroup) {
  50. while (true) {
  51. std::function<void()> Task;
  52. ThreadPoolTaskGroup *GroupOfTask;
  53. {
  54. std::unique_lock<std::mutex> LockGuard(QueueLock);
  55. bool workCompletedForGroup = false; // Result of workCompletedUnlocked()
  56. // Wait for tasks to be pushed in the queue
  57. QueueCondition.wait(LockGuard, [&] {
  58. return !EnableFlag || !Tasks.empty() ||
  59. (WaitingForGroup != nullptr &&
  60. (workCompletedForGroup =
  61. workCompletedUnlocked(WaitingForGroup)));
  62. });
  63. // Exit condition
  64. if (!EnableFlag && Tasks.empty())
  65. return;
  66. if (WaitingForGroup != nullptr && workCompletedForGroup)
  67. return;
  68. // Yeah, we have a task, grab it and release the lock on the queue
  69. // We first need to signal that we are active before popping the queue
  70. // in order for wait() to properly detect that even if the queue is
  71. // empty, there is still a task in flight.
  72. ++ActiveThreads;
  73. Task = std::move(Tasks.front().first);
  74. GroupOfTask = Tasks.front().second;
  75. // Need to count active threads in each group separately, ActiveThreads
  76. // would never be 0 if waiting for another group inside a wait.
  77. if (GroupOfTask != nullptr)
  78. ++ActiveGroups[GroupOfTask]; // Increment or set to 1 if new item
  79. Tasks.pop_front();
  80. }
  81. #ifndef NDEBUG
  82. if (CurrentThreadTaskGroups == nullptr)
  83. CurrentThreadTaskGroups = new std::vector<ThreadPoolTaskGroup *>;
  84. CurrentThreadTaskGroups->push_back(GroupOfTask);
  85. #endif
  86. // Run the task we just grabbed
  87. Task();
  88. #ifndef NDEBUG
  89. CurrentThreadTaskGroups->pop_back();
  90. if (CurrentThreadTaskGroups->empty()) {
  91. delete CurrentThreadTaskGroups;
  92. CurrentThreadTaskGroups = nullptr;
  93. }
  94. #endif
  95. bool Notify;
  96. bool NotifyGroup;
  97. {
  98. // Adjust `ActiveThreads`, in case someone waits on ThreadPool::wait()
  99. std::lock_guard<std::mutex> LockGuard(QueueLock);
  100. --ActiveThreads;
  101. if (GroupOfTask != nullptr) {
  102. auto A = ActiveGroups.find(GroupOfTask);
  103. if (--(A->second) == 0)
  104. ActiveGroups.erase(A);
  105. }
  106. Notify = workCompletedUnlocked(GroupOfTask);
  107. NotifyGroup = GroupOfTask != nullptr && Notify;
  108. }
  109. // Notify task completion if this is the last active thread, in case
  110. // someone waits on ThreadPool::wait().
  111. if (Notify)
  112. CompletionCondition.notify_all();
  113. // If this was a task in a group, notify also threads waiting for tasks
  114. // in this function on QueueCondition, to make a recursive wait() return
  115. // after the group it's been waiting for has finished.
  116. if (NotifyGroup)
  117. QueueCondition.notify_all();
  118. }
  119. }
  120. bool ThreadPool::workCompletedUnlocked(ThreadPoolTaskGroup *Group) const {
  121. if (Group == nullptr)
  122. return !ActiveThreads && Tasks.empty();
  123. return ActiveGroups.count(Group) == 0 &&
  124. !llvm::any_of(Tasks,
  125. [Group](const auto &T) { return T.second == Group; });
  126. }
  127. void ThreadPool::wait() {
  128. assert(!isWorkerThread()); // Would deadlock waiting for itself.
  129. // Wait for all threads to complete and the queue to be empty
  130. std::unique_lock<std::mutex> LockGuard(QueueLock);
  131. CompletionCondition.wait(LockGuard,
  132. [&] { return workCompletedUnlocked(nullptr); });
  133. }
  134. void ThreadPool::wait(ThreadPoolTaskGroup &Group) {
  135. // Wait for all threads in the group to complete.
  136. if (!isWorkerThread()) {
  137. std::unique_lock<std::mutex> LockGuard(QueueLock);
  138. CompletionCondition.wait(LockGuard,
  139. [&] { return workCompletedUnlocked(&Group); });
  140. return;
  141. }
  142. // Make sure to not deadlock waiting for oneself.
  143. assert(CurrentThreadTaskGroups == nullptr ||
  144. !llvm::is_contained(*CurrentThreadTaskGroups, &Group));
  145. // Handle the case of recursive call from another task in a different group,
  146. // in which case process tasks while waiting to keep the thread busy and avoid
  147. // possible deadlock.
  148. processTasks(&Group);
  149. }
  150. bool ThreadPool::isWorkerThread() const {
  151. llvm::sys::ScopedReader LockGuard(ThreadsLock);
  152. llvm::thread::id CurrentThreadId = llvm::this_thread::get_id();
  153. for (const llvm::thread &Thread : Threads)
  154. if (CurrentThreadId == Thread.get_id())
  155. return true;
  156. return false;
  157. }
  158. // The destructor joins all threads, waiting for completion.
  159. ThreadPool::~ThreadPool() {
  160. {
  161. std::unique_lock<std::mutex> LockGuard(QueueLock);
  162. EnableFlag = false;
  163. }
  164. QueueCondition.notify_all();
  165. llvm::sys::ScopedReader LockGuard(ThreadsLock);
  166. for (auto &Worker : Threads)
  167. Worker.join();
  168. }
  169. #else // LLVM_ENABLE_THREADS Disabled
  170. // No threads are launched, issue a warning if ThreadCount is not 0
  171. ThreadPool::ThreadPool(ThreadPoolStrategy S) : MaxThreadCount(1) {
  172. int ThreadCount = S.compute_thread_count();
  173. if (ThreadCount != 1) {
  174. errs() << "Warning: request a ThreadPool with " << ThreadCount
  175. << " threads, but LLVM_ENABLE_THREADS has been turned off\n";
  176. }
  177. }
  178. void ThreadPool::wait() {
  179. // Sequential implementation running the tasks
  180. while (!Tasks.empty()) {
  181. auto Task = std::move(Tasks.front().first);
  182. Tasks.pop_front();
  183. Task();
  184. }
  185. }
  186. void ThreadPool::wait(ThreadPoolTaskGroup &) {
  187. // Simply wait for all, this works even if recursive (the running task
  188. // is already removed from the queue).
  189. wait();
  190. }
  191. bool ThreadPool::isWorkerThread() const {
  192. report_fatal_error("LLVM compiled without multithreading");
  193. }
  194. ThreadPool::~ThreadPool() { wait(); }
  195. #endif