LLVM  16.0.0git
ThreadPool.cpp
Go to the documentation of this file.
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 
14 
15 #include "llvm/Config/llvm-config.h"
16 
17 #if LLVM_ENABLE_THREADS
18 #include "llvm/Support/Threading.h"
19 #else
21 #endif
22 
23 using namespace llvm;
24 
25 #if LLVM_ENABLE_THREADS
26 
27 // A note on thread groups: Tasks are by default in no group (represented
28 // by nullptr ThreadPoolTaskGroup pointer in the Tasks queue) and functionality
29 // here normally works on all tasks regardless of their group (functions
30 // in that case receive nullptr ThreadPoolTaskGroup pointer as argument).
31 // A task in a group has a pointer to that ThreadPoolTaskGroup in the Tasks
32 // queue, and functions called to work only on tasks from one group take that
33 // pointer.
34 
36  : Strategy(S), MaxThreadCount(S.compute_thread_count()) {}
37 
38 void ThreadPool::grow(int requested) {
39  llvm::sys::ScopedWriter LockGuard(ThreadsLock);
40  if (Threads.size() >= MaxThreadCount)
41  return; // Already hit the max thread pool size.
42  int newThreadCount = std::min<int>(requested, MaxThreadCount);
43  while (static_cast<int>(Threads.size()) < newThreadCount) {
44  int ThreadID = Threads.size();
45  Threads.emplace_back([this, ThreadID] {
46  Strategy.apply_thread_strategy(ThreadID);
47  processTasks(nullptr);
48  });
49  }
50 }
51 
52 #ifndef NDEBUG
53 // The group of the tasks run by the current thread.
54 static LLVM_THREAD_LOCAL std::vector<ThreadPoolTaskGroup *>
56 #endif
57 
58 // WaitingForGroup == nullptr means all tasks regardless of their group.
59 void ThreadPool::processTasks(ThreadPoolTaskGroup *WaitingForGroup) {
60  while (true) {
61  std::function<void()> Task;
62  ThreadPoolTaskGroup *GroupOfTask;
63  {
64  std::unique_lock<std::mutex> LockGuard(QueueLock);
65  bool workCompletedForGroup = false; // Result of workCompletedUnlocked()
66  // Wait for tasks to be pushed in the queue
67  QueueCondition.wait(LockGuard, [&] {
68  return !EnableFlag || !Tasks.empty() ||
69  (WaitingForGroup != nullptr &&
70  (workCompletedForGroup =
71  workCompletedUnlocked(WaitingForGroup)));
72  });
73  // Exit condition
74  if (!EnableFlag && Tasks.empty())
75  return;
76  if (WaitingForGroup != nullptr && workCompletedForGroup)
77  return;
78  // Yeah, we have a task, grab it and release the lock on the queue
79 
80  // We first need to signal that we are active before popping the queue
81  // in order for wait() to properly detect that even if the queue is
82  // empty, there is still a task in flight.
83  ++ActiveThreads;
84  Task = std::move(Tasks.front().first);
85  GroupOfTask = Tasks.front().second;
86  // Need to count active threads in each group separately, ActiveThreads
87  // would never be 0 if waiting for another group inside a wait.
88  if (GroupOfTask != nullptr)
89  ++ActiveGroups[GroupOfTask]; // Increment or set to 1 if new item
90  Tasks.pop_front();
91  }
92 #ifndef NDEBUG
93  if (CurrentThreadTaskGroups == nullptr)
94  CurrentThreadTaskGroups = new std::vector<ThreadPoolTaskGroup *>;
95  CurrentThreadTaskGroups->push_back(GroupOfTask);
96 #endif
97 
98  // Run the task we just grabbed
99  Task();
100 
101 #ifndef NDEBUG
102  CurrentThreadTaskGroups->pop_back();
103  if (CurrentThreadTaskGroups->empty()) {
105  CurrentThreadTaskGroups = nullptr;
106  }
107 #endif
108 
109  bool Notify;
110  bool NotifyGroup;
111  {
112  // Adjust `ActiveThreads`, in case someone waits on ThreadPool::wait()
113  std::lock_guard<std::mutex> LockGuard(QueueLock);
114  --ActiveThreads;
115  if (GroupOfTask != nullptr) {
116  auto A = ActiveGroups.find(GroupOfTask);
117  if (--(A->second) == 0)
118  ActiveGroups.erase(A);
119  }
120  Notify = workCompletedUnlocked(GroupOfTask);
121  NotifyGroup = GroupOfTask != nullptr && Notify;
122  }
123  // Notify task completion if this is the last active thread, in case
124  // someone waits on ThreadPool::wait().
125  if (Notify)
126  CompletionCondition.notify_all();
127  // If this was a task in a group, notify also threads waiting for tasks
128  // in this function on QueueCondition, to make a recursive wait() return
129  // after the group it's been waiting for has finished.
130  if (NotifyGroup)
131  QueueCondition.notify_all();
132  }
133 }
134 
135 bool ThreadPool::workCompletedUnlocked(ThreadPoolTaskGroup *Group) const {
136  if (Group == nullptr)
137  return !ActiveThreads && Tasks.empty();
138  return ActiveGroups.count(Group) == 0 &&
139  !llvm::any_of(Tasks,
140  [Group](const auto &T) { return T.second == Group; });
141 }
142 
144  assert(!isWorkerThread()); // Would deadlock waiting for itself.
145  // Wait for all threads to complete and the queue to be empty
146  std::unique_lock<std::mutex> LockGuard(QueueLock);
147  CompletionCondition.wait(LockGuard,
148  [&] { return workCompletedUnlocked(nullptr); });
149 }
150 
152  // Wait for all threads in the group to complete.
153  if (!isWorkerThread()) {
154  std::unique_lock<std::mutex> LockGuard(QueueLock);
155  CompletionCondition.wait(LockGuard,
156  [&] { return workCompletedUnlocked(&Group); });
157  return;
158  }
159  // Make sure to not deadlock waiting for oneself.
160  assert(CurrentThreadTaskGroups == nullptr ||
162  // Handle the case of recursive call from another task in a different group,
163  // in which case process tasks while waiting to keep the thread busy and avoid
164  // possible deadlock.
165  processTasks(&Group);
166 }
167 
169  llvm::sys::ScopedReader LockGuard(ThreadsLock);
170  llvm::thread::id CurrentThreadId = llvm::this_thread::get_id();
171  for (const llvm::thread &Thread : Threads)
172  if (CurrentThreadId == Thread.get_id())
173  return true;
174  return false;
175 }
176 
177 // The destructor joins all threads, waiting for completion.
179  {
180  std::unique_lock<std::mutex> LockGuard(QueueLock);
181  EnableFlag = false;
182  }
183  QueueCondition.notify_all();
184  llvm::sys::ScopedReader LockGuard(ThreadsLock);
185  for (auto &Worker : Threads)
186  Worker.join();
187 }
188 
189 #else // LLVM_ENABLE_THREADS Disabled
190 
191 // No threads are launched, issue a warning if ThreadCount is not 0
192 ThreadPool::ThreadPool(ThreadPoolStrategy S) : MaxThreadCount(1) {
193  int ThreadCount = S.compute_thread_count();
194  if (ThreadCount != 1) {
195  errs() << "Warning: request a ThreadPool with " << ThreadCount
196  << " threads, but LLVM_ENABLE_THREADS has been turned off\n";
197  }
198 }
199 
200 void ThreadPool::wait() {
201  // Sequential implementation running the tasks
202  while (!Tasks.empty()) {
203  auto Task = std::move(Tasks.front().first);
204  Tasks.pop_front();
205  Task();
206  }
207 }
208 
210  // Simply wait for all, this works even if recursive (the running task
211  // is already removed from the queue).
212  wait();
213 }
214 
215 bool ThreadPool::isWorkerThread() const {
216  report_fatal_error("LLVM compiled without multithreading");
217 }
218 
220 
221 #endif
llvm::this_thread::get_id
thread::id get_id()
Definition: thread.h:157
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
T
Thread
uint64_t Thread
Definition: Profile.cpp:48
llvm::ThreadPoolStrategy
This tells how a thread pool will be used.
Definition: Threading.h:116
llvm::ThreadPool::ThreadPool
ThreadPool(ThreadPoolStrategy S=hardware_concurrency())
Construct a pool using the hardware strategy S for mapping hardware execution resources (threads,...
Definition: ThreadPool.cpp:35
llvm::errs
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Definition: raw_ostream.cpp:891
LLVM_THREAD_LOCAL
#define LLVM_THREAD_LOCAL
\macro LLVM_THREAD_LOCAL A thread-local storage specifier which can be used with globals,...
Definition: Compiler.h:527
llvm::thread::id
pthread_t id
Definition: thread.h:56
llvm::report_fatal_error
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:145
llvm::ThreadPoolStrategy::apply_thread_strategy
void apply_thread_strategy(unsigned ThreadPoolNum) const
Assign the current thread to an ideal hardware CPU or NUMA node.
llvm::sys::ScopedWriter
SmartScopedWriter< false > ScopedWriter
Definition: RWMutex.h:190
ThreadPool.h
Threading.h
llvm::ThreadPoolTaskGroup
A group of tasks to be run on a thread pool.
Definition: ThreadPool.h:224
llvm::thread
LLVM thread following std::thread interface with added constructor to specify stack size.
Definition: thread.h:38
move
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
Definition: README.txt:546
llvm::ThreadPool::isWorkerThread
bool isWorkerThread() const
Returns true if the current thread is a worker thread of this thread pool.
Definition: ThreadPool.cpp:168
llvm::is_contained
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.
Definition: STLExtras.h:1868
llvm::ThreadPool::~ThreadPool
~ThreadPool()
Blocking destructor: the pool will wait for all the threads to complete.
Definition: ThreadPool.cpp:178
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
function
print Print MemDeps of function
Definition: MemDepPrinter.cpp:82
llvm::any_of
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1741
S
add sub stmia L5 ldr r0 bl L_printf $stub Instead of a and a wouldn t it be better to do three moves *Return an aggregate type is even return S
Definition: README.txt:210
CurrentThreadTaskGroups
static LLVM_THREAD_LOCAL std::vector< ThreadPoolTaskGroup * > * CurrentThreadTaskGroups
Definition: ThreadPool.cpp:55
llvm::sys::ScopedReader
SmartScopedReader< false > ScopedReader
Definition: RWMutex.h:173
llvm::ThreadPool::wait
void wait()
Blocking wait for all the threads to complete and the queue to be empty.
Definition: ThreadPool.cpp:143
raw_ostream.h