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
25
26namespace llvm {
27namespace parallel {
28#if LLVM_ENABLE_THREADS
29
30#ifdef _WIN32
31static thread_local unsigned threadIndex = UINT_MAX;
32
33unsigned getThreadIndex() { GET_THREAD_INDEX_IMPL; }
34#else
35thread_local unsigned threadIndex = UINT_MAX;
36#endif
37
38namespace detail {
39
40namespace {
41
42/// An abstract class that takes closures and runs them asynchronously.
43class Executor {
44public:
45 virtual ~Executor() = default;
46 virtual void add(std::function<void()> func) = 0;
47 virtual size_t getThreadCount() const = 0;
48
49 static Executor *getDefaultExecutor();
50};
51
52/// An implementation of an Executor that runs closures on a thread pool
53/// in filo order.
54class ThreadPoolExecutor : public Executor {
55public:
56 explicit ThreadPoolExecutor(ThreadPoolStrategy S) {
57 if (S.UseJobserver)
58 TheJobserver = JobserverClient::getInstance();
59
61 // Spawn all but one of the threads in another thread as spawning threads
62 // can take a while.
63 Threads.reserve(ThreadCount);
64 Threads.resize(1);
65 std::lock_guard<std::mutex> Lock(Mutex);
66 // Use operator[] before creating the thread to avoid data race in .size()
67 // in 'safe libc++' mode.
68 auto &Thread0 = Threads[0];
69 Thread0 = std::thread([this, S] {
70 for (unsigned I = 1; I < ThreadCount; ++I) {
71 Threads.emplace_back([this, S, I] { work(S, I); });
72 if (Stop)
73 break;
74 }
75 ThreadsCreated.set_value();
76 work(S, 0);
77 });
78 }
79
80 // To make sure the thread pool executor can only be created with a parallel
81 // strategy.
82 ThreadPoolExecutor() = delete;
83
84 void stop() {
85 {
86 std::lock_guard<std::mutex> Lock(Mutex);
87 if (Stop)
88 return;
89 Stop = true;
90 }
91 Cond.notify_all();
92 ThreadsCreated.get_future().wait();
93 }
94
95 ~ThreadPoolExecutor() override {
96 stop();
97 std::thread::id CurrentThreadId = std::this_thread::get_id();
98 for (std::thread &T : Threads)
99 if (T.get_id() == CurrentThreadId)
100 T.detach();
101 else
102 T.join();
103 }
104
105 struct Creator {
106 static void *call() { return new ThreadPoolExecutor(strategy); }
107 };
108 struct Deleter {
109 static void call(void *Ptr) { ((ThreadPoolExecutor *)Ptr)->stop(); }
110 };
111
112 void add(std::function<void()> F) override {
113 {
114 std::lock_guard<std::mutex> Lock(Mutex);
115 WorkStack.push_back(std::move(F));
116 }
117 Cond.notify_one();
118 }
119
120 size_t getThreadCount() const override { return ThreadCount; }
121
122private:
123 void work(ThreadPoolStrategy S, unsigned ThreadID) {
124 threadIndex = ThreadID;
125 S.apply_thread_strategy(ThreadID);
126 // Note on jobserver deadlock avoidance:
127 // GNU Make grants each invoked process one implicit job slot. Our
128 // JobserverClient models this by returning an implicit JobSlot on the
129 // first successful tryAcquire() in a process. This guarantees forward
130 // progress without requiring a dedicated "always-on" thread here.
131
132 while (true) {
133 if (TheJobserver) {
134 // Jobserver-mode scheduling:
135 // - Acquire one job slot (with exponential backoff to avoid busy-wait).
136 // - While holding the slot, drain and run tasks from the local queue.
137 // - Release the slot when the queue is empty or when shutting down.
138 // Rationale: Holding a slot amortizes acquire/release overhead over
139 // multiple tasks and avoids requeue/yield churn, while still enforcing
140 // the jobserver’s global concurrency limit. With K available slots,
141 // up to K workers run tasks in parallel; within each worker tasks run
142 // sequentially until the local queue is empty.
143 ExponentialBackoff Backoff(std::chrono::hours(24));
144 JobSlot Slot;
145 do {
146 if (Stop)
147 return;
148 Slot = TheJobserver->tryAcquire();
149 if (Slot.isValid())
150 break;
151 } while (Backoff.waitForNextAttempt());
152
153 llvm::scope_exit SlotReleaser(
154 [&] { TheJobserver->release(std::move(Slot)); });
155
156 while (true) {
157 std::function<void()> Task;
158 {
159 std::unique_lock<std::mutex> Lock(Mutex);
160 Cond.wait(Lock, [&] { return Stop || !WorkStack.empty(); });
161 if (Stop && WorkStack.empty())
162 return;
163 if (WorkStack.empty())
164 break;
165 Task = std::move(WorkStack.back());
166 WorkStack.pop_back();
167 }
168 Task();
169 }
170 } else {
171 std::unique_lock<std::mutex> Lock(Mutex);
172 Cond.wait(Lock, [&] { return Stop || !WorkStack.empty(); });
173 if (Stop)
174 break;
175 auto Task = std::move(WorkStack.back());
176 WorkStack.pop_back();
177 Lock.unlock();
178 Task();
179 }
180 }
181 }
182
183 std::atomic<bool> Stop{false};
184 std::vector<std::function<void()>> WorkStack;
185 std::mutex Mutex;
186 std::condition_variable Cond;
187 std::promise<void> ThreadsCreated;
188 std::vector<std::thread> Threads;
189 unsigned ThreadCount;
190
191 JobserverClient *TheJobserver = nullptr;
192};
193
194Executor *Executor::getDefaultExecutor() {
195#ifdef _WIN32
196 // The ManagedStatic enables the ThreadPoolExecutor to be stopped via
197 // llvm_shutdown() which allows a "clean" fast exit, e.g. via _exit(). This
198 // stops the thread pool and waits for any worker thread creation to complete
199 // but does not wait for the threads to finish. The wait for worker thread
200 // creation to complete is important as it prevents intermittent crashes on
201 // Windows due to a race condition between thread creation and process exit.
202 //
203 // The ThreadPoolExecutor will only be destroyed when the static unique_ptr to
204 // it is destroyed, i.e. in a normal full exit. The ThreadPoolExecutor
205 // destructor ensures it has been stopped and waits for worker threads to
206 // finish. The wait is important as it prevents intermittent crashes on
207 // Windows when the process is doing a full exit.
208 //
209 // The Windows crashes appear to only occur with the MSVC static runtimes and
210 // are more frequent with the debug static runtime.
211 //
212 // This also prevents intermittent deadlocks on exit with the MinGW runtime.
213
214 static ManagedStatic<ThreadPoolExecutor, ThreadPoolExecutor::Creator,
215 ThreadPoolExecutor::Deleter>
216 ManagedExec;
217 static std::unique_ptr<ThreadPoolExecutor> Exec(&(*ManagedExec));
218 return Exec.get();
219#else
220 // ManagedStatic is not desired on other platforms. When `Exec` is destroyed
221 // by llvm_shutdown(), worker threads will clean up and invoke TLS
222 // destructors. This can lead to race conditions if other threads attempt to
223 // access TLS objects that have already been destroyed.
224 static ThreadPoolExecutor Exec(strategy);
225 return &Exec;
226#endif
227}
228} // namespace
229} // namespace detail
230
231size_t getThreadCount() {
232 return detail::Executor::getDefaultExecutor()->getThreadCount();
233}
234#endif
235
236// Latch::sync() called by the dtor may cause one thread to block. If is a dead
237// lock if all threads in the default executor are blocked. To prevent the dead
238// lock, only allow the root TaskGroup to run tasks parallelly. In the scenario
239// of nested parallel_for_each(), only the outermost one runs parallelly.
241#if LLVM_ENABLE_THREADS
242 : Parallel((parallel::strategy.ThreadsRequested != 1) &&
243 (threadIndex == UINT_MAX)) {}
244#else
245 : Parallel(false) {}
246#endif
248 // We must ensure that all the workloads have finished before decrementing the
249 // instances count.
250 L.sync();
251}
252
253void TaskGroup::spawn(std::function<void()> F) {
254#if LLVM_ENABLE_THREADS
255 if (Parallel) {
256 L.inc();
257 detail::Executor::getDefaultExecutor()->add([&, F = std::move(F)] {
258 F();
259 L.dec();
260 });
261 return;
262 }
263#endif
264 F();
265}
266
267} // namespace parallel
268} // namespace llvm
269
270void llvm::parallelFor(size_t Begin, size_t End,
271 llvm::function_ref<void(size_t)> Fn) {
272#if LLVM_ENABLE_THREADS
273 if (parallel::strategy.ThreadsRequested != 1) {
274 auto NumItems = End - Begin;
275 // Limit the number of tasks to MaxTasksPerGroup to limit job scheduling
276 // overhead on large inputs.
277 auto TaskSize = NumItems / parallel::detail::MaxTasksPerGroup;
278 if (TaskSize == 0)
279 TaskSize = 1;
280
282 for (; Begin + TaskSize < End; Begin += TaskSize) {
283 TG.spawn([=, &Fn] {
284 for (size_t I = Begin, E = Begin + TaskSize; I != E; ++I)
285 Fn(I);
286 });
287 }
288 if (Begin != End) {
289 TG.spawn([=, &Fn] {
290 for (size_t I = Begin; I != End; ++I)
291 Fn(I);
292 });
293 }
294 return;
295 }
296#endif
297
298 for (; Begin != End; ++Begin)
299 Fn(Begin);
300}
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
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))
A class to help implement exponential backoff.
LLVM_ABI bool waitForNextAttempt()
Blocks while waiting for the next attempt.
A JobSlot represents a single job slot that can be acquired from or released to a jobserver pool.
Definition Jobserver.h:75
The public interface for a jobserver client.
Definition Jobserver.h:133
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:42
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:253
LLVM_ABI ThreadPoolStrategy strategy
Definition Parallel.cpp:24
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.
Definition Types.h:26
LLVM_ABI void parallelFor(size_t Begin, size_t End, function_ref< void(size_t)> Fn)
Definition Parallel.cpp:270