LLVM 23.0.0git
Parallel.cpp
Go to the documentation of this file.
1//===- llvm/Support/Parallel.cpp - Parallel algorithms --------------------===//
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
10#include "llvm/ADT/ScopeExit.h"
11#include "llvm/Config/llvm-config.h"
16
17#include <atomic>
18#include <future>
19#include <memory>
20#include <mutex>
21#include <thread>
22#include <vector>
23
24using namespace llvm;
25using namespace llvm::parallel;
26
28
29#if LLVM_ENABLE_THREADS
30
31#ifdef _WIN32
32static thread_local unsigned threadIndex = UINT_MAX;
33
34unsigned parallel::getThreadIndex() { GET_THREAD_INDEX_IMPL; }
35#else
36thread_local unsigned parallel::threadIndex = UINT_MAX;
37#endif
38
39namespace {
40
41/// Runs closures on a thread pool in filo order.
42class ThreadPoolExecutor {
43public:
44 explicit ThreadPoolExecutor(ThreadPoolStrategy S) {
45 if (S.UseJobserver)
46 TheJobserver = JobserverClient::getInstance();
47
49 // Spawn all but one of the threads in another thread as spawning threads
50 // can take a while.
51 Threads.reserve(ThreadCount);
52 Threads.resize(1);
53 std::lock_guard<std::mutex> Lock(Mutex);
54 // Use operator[] before creating the thread to avoid data race in .size()
55 // in 'safe libc++' mode.
56 auto &Thread0 = Threads[0];
57 Thread0 = std::thread([this, S] {
58 for (unsigned I = 1; I < ThreadCount; ++I) {
59 Threads.emplace_back([this, S, I] { work(S, I); });
60 if (Stop)
61 break;
62 }
63 ThreadsCreated.set_value();
64 work(S, 0);
65 });
66 }
67
68 // To make sure the thread pool executor can only be created with a parallel
69 // strategy.
70 ThreadPoolExecutor() = delete;
71
72 void stop() {
73 {
74 std::lock_guard<std::mutex> Lock(Mutex);
75 if (Stop)
76 return;
77 Stop = true;
78 }
79 Cond.notify_all();
80 ThreadsCreated.get_future().wait();
81
82 std::thread::id CurrentThreadId = std::this_thread::get_id();
83 for (std::thread &T : Threads)
84 if (T.get_id() == CurrentThreadId)
85 T.detach();
86 else
87 T.join();
88 }
89
90 ~ThreadPoolExecutor() { stop(); }
91
92 struct Creator {
93 static void *call() { return new ThreadPoolExecutor(strategy); }
94 };
95 struct Deleter {
96 static void call(void *Ptr) { ((ThreadPoolExecutor *)Ptr)->stop(); }
97 };
98
99 void add(std::function<void()> F) {
100 {
101 std::lock_guard<std::mutex> Lock(Mutex);
102 WorkStack.push_back(std::move(F));
103 }
104 Cond.notify_one();
105 }
106
107 size_t getThreadCount() const { return ThreadCount; }
108
109private:
110 void work(ThreadPoolStrategy S, unsigned ThreadID) {
111 threadIndex = ThreadID;
112 S.apply_thread_strategy(ThreadID);
113 // Note on jobserver deadlock avoidance:
114 // GNU Make grants each invoked process one implicit job slot. Our
115 // JobserverClient models this by returning an implicit JobSlot on the
116 // first successful tryAcquire() in a process. This guarantees forward
117 // progress without requiring a dedicated "always-on" thread here.
118
119 while (true) {
120 if (TheJobserver) {
121 // Jobserver-mode scheduling:
122 // - Acquire one job slot (with exponential backoff to avoid busy-wait).
123 // - While holding the slot, drain and run tasks from the local queue.
124 // - Release the slot when the queue is empty or when shutting down.
125 // Rationale: Holding a slot amortizes acquire/release overhead over
126 // multiple tasks and avoids requeue/yield churn, while still enforcing
127 // the jobserver’s global concurrency limit. With K available slots,
128 // up to K workers run tasks in parallel; within each worker tasks run
129 // sequentially until the local queue is empty.
130 ExponentialBackoff Backoff(std::chrono::hours(24));
131 JobSlot Slot;
132 do {
133 if (Stop)
134 return;
135 Slot = TheJobserver->tryAcquire();
136 if (Slot.isValid())
137 break;
138 } while (Backoff.waitForNextAttempt());
139
140 llvm::scope_exit SlotReleaser(
141 [&] { TheJobserver->release(std::move(Slot)); });
142
143 while (true) {
144 std::function<void()> Task;
145 {
146 std::unique_lock<std::mutex> Lock(Mutex);
147 Cond.wait(Lock, [&] { return Stop || !WorkStack.empty(); });
148 if (Stop && WorkStack.empty())
149 return;
150 if (WorkStack.empty())
151 break;
152 Task = std::move(WorkStack.back());
153 WorkStack.pop_back();
154 }
155 Task();
156 }
157 } else {
158 std::unique_lock<std::mutex> Lock(Mutex);
159 Cond.wait(Lock, [&] { return Stop || !WorkStack.empty(); });
160 if (Stop)
161 break;
162 auto Task = std::move(WorkStack.back());
163 WorkStack.pop_back();
164 Lock.unlock();
165 Task();
166 }
167 }
168 }
169
170 std::atomic<bool> Stop{false};
171 std::vector<std::function<void()>> WorkStack;
172 std::mutex Mutex;
173 std::condition_variable Cond;
174 std::promise<void> ThreadsCreated;
175 std::vector<std::thread> Threads;
176 unsigned ThreadCount;
177
178 JobserverClient *TheJobserver = nullptr;
179};
180} // namespace
181
182static ThreadPoolExecutor *getDefaultExecutor() {
183#ifdef _WIN32
184 // The ManagedStatic enables the ThreadPoolExecutor to be stopped via
185 // llvm_shutdown() on Windows. This is important to avoid various race
186 // conditions at process exit that can cause crashes or deadlocks.
187
188 static ManagedStatic<ThreadPoolExecutor, ThreadPoolExecutor::Creator,
189 ThreadPoolExecutor::Deleter>
190 ManagedExec;
191 static std::unique_ptr<ThreadPoolExecutor> Exec(&(*ManagedExec));
192 return Exec.get();
193#else
194 // ManagedStatic is not desired on other platforms. When `Exec` is destroyed
195 // by llvm_shutdown(), worker threads will clean up and invoke TLS
196 // destructors. This can lead to race conditions if other threads attempt to
197 // access TLS objects that have already been destroyed.
198 static ThreadPoolExecutor Exec(strategy);
199 return &Exec;
200#endif
201}
202
204 return getDefaultExecutor()->getThreadCount();
205}
206#endif
207
208// Latch::sync() called by the dtor may cause one thread to block. If is a dead
209// lock if all threads in the default executor are blocked. To prevent the dead
210// lock, only allow the root TaskGroup to run tasks parallelly. In the scenario
211// of nested parallel_for_each(), only the outermost one runs parallelly.
213 : Parallel(
214#if LLVM_ENABLE_THREADS
215 strategy.ThreadsRequested != 1 && threadIndex == UINT_MAX
216#else
217 false
218#endif
219 ) {
220}
222 // We must ensure that all the workloads have finished before decrementing the
223 // instances count.
224 L.sync();
225}
226
227void TaskGroup::spawn(std::function<void()> F) {
228#if LLVM_ENABLE_THREADS
229 if (Parallel) {
230 L.inc();
231 getDefaultExecutor()->add([&, F = std::move(F)] {
232 F();
233 L.dec();
234 });
235 return;
236 }
237#endif
238 F();
239}
240
241void llvm::parallelFor(size_t Begin, size_t End,
242 function_ref<void(size_t)> Fn) {
243#if LLVM_ENABLE_THREADS
244 if (strategy.ThreadsRequested != 1) {
245 size_t NumItems = End - Begin;
246 if (NumItems == 0)
247 return;
248 // Distribute work via an atomic counter shared by NumWorkers threads,
249 // keeping the task count (and thus Linux futex calls) at O(ThreadCount)
250 // For lld, per-file work is somewhat uneven, so a multipler > 1 is safer.
251 // While 2 vs 4 vs 8 makes no measurable difference, 4 is used as a
252 // reasonable default.
253 size_t NumWorkers = std::min<size_t>(NumItems, getThreadCount());
254 size_t ChunkSize = std::max(size_t(1), NumItems / (NumWorkers * 4));
255 std::atomic<size_t> Idx{Begin};
256 auto Worker = [&] {
257 while (true) {
258 size_t I = Idx.fetch_add(ChunkSize, std::memory_order_relaxed);
259 if (I >= End)
260 break;
261 size_t IEnd = std::min(I + ChunkSize, End);
262 for (; I < IEnd; ++I)
263 Fn(I);
264 }
265 };
266
267 TaskGroup TG;
268 for (size_t I = 0; I != NumWorkers; ++I)
269 TG.spawn(Worker);
270 return;
271 }
272#endif
273
274 for (; Begin != End; ++Begin)
275 Fn(Begin);
276}
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
if(PassOpts->AAPipeline)
const SmallVectorImpl< MachineOperand > & Cond
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
static cl::opt< int > ThreadCount("threads", cl::init(0))
static LLVM_ABI_FOR_TEST JobserverClient * getInstance()
Returns the singleton instance of the JobserverClient.
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
This tells how a thread pool will be used.
Definition Threading.h:115
LLVM_ABI void apply_thread_strategy(unsigned ThreadPoolNum) const
Assign the current thread to an ideal hardware CPU or NUMA node.
LLVM_ABI unsigned compute_thread_count() const
Retrieves the max available threads for the current strategy.
Definition Threading.cpp:43
bool UseJobserver
If true, the thread pool will attempt to coordinate with a GNU Make jobserver, acquiring a job slot b...
Definition Threading.h:149
An efficient, type-erasing, non-owning reference to a callable.
LLVM_ABI void spawn(std::function< void()> f)
Definition Parallel.cpp:227
LLVM_ABI ThreadPoolStrategy strategy
Definition Parallel.cpp:27
unsigned getThreadIndex()
Definition Parallel.h:55
size_t getThreadCount()
Definition Parallel.h:56
SmartMutex< false > Mutex
Mutex - A standard, always enforced mutex.
Definition Mutex.h:66
This is an optimization pass for GlobalISel generic memory operations.
scope_exit(Callable) -> scope_exit< Callable >
LLVM_ABI void parallelFor(size_t Begin, size_t End, function_ref< void(size_t)> Fn)
Definition Parallel.cpp:241