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 9 #include "llvm/Support/Parallel.h" 10 #include "llvm/Config/llvm-config.h" 11 #include "llvm/Support/ManagedStatic.h" 12 #include "llvm/Support/Threading.h" 13 14 #include <atomic> 15 #include <deque> 16 #include <future> 17 #include <thread> 18 #include <vector> 19 20 llvm::ThreadPoolStrategy llvm::parallel::strategy; 21 22 namespace llvm { 23 namespace parallel { 24 #if LLVM_ENABLE_THREADS 25 26 #ifdef _WIN32 27 static thread_local unsigned threadIndex = UINT_MAX; 28 29 unsigned getThreadIndex() { GET_THREAD_INDEX_IMPL; } 30 #else 31 thread_local unsigned threadIndex = UINT_MAX; 32 #endif 33 34 namespace detail { 35 36 namespace { 37 38 /// An abstract class that takes closures and runs them asynchronously. 39 class Executor { 40 public: 41 virtual ~Executor() = default; 42 virtual void add(std::function<void()> func, bool Sequential = false) = 0; 43 44 static Executor *getDefaultExecutor(); 45 }; 46 47 /// An implementation of an Executor that runs closures on a thread pool 48 /// in filo order. 49 class ThreadPoolExecutor : public Executor { 50 public: 51 explicit ThreadPoolExecutor(ThreadPoolStrategy S = hardware_concurrency()) { 52 unsigned ThreadCount = S.compute_thread_count(); 53 // Spawn all but one of the threads in another thread as spawning threads 54 // can take a while. 55 Threads.reserve(ThreadCount); 56 Threads.resize(1); 57 std::lock_guard<std::mutex> Lock(Mutex); 58 // Use operator[] before creating the thread to avoid data race in .size() 59 // in “safe libc++” mode. 60 auto &Thread0 = Threads[0]; 61 Thread0 = std::thread([this, ThreadCount, S] { 62 for (unsigned I = 1; I < ThreadCount; ++I) { 63 Threads.emplace_back([=] { work(S, I); }); 64 if (Stop) 65 break; 66 } 67 ThreadsCreated.set_value(); 68 work(S, 0); 69 }); 70 } 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 83 ~ThreadPoolExecutor() override { 84 stop(); 85 std::thread::id CurrentThreadId = std::this_thread::get_id(); 86 for (std::thread &T : Threads) 87 if (T.get_id() == CurrentThreadId) 88 T.detach(); 89 else 90 T.join(); 91 } 92 93 struct Creator { 94 static void *call() { return new ThreadPoolExecutor(strategy); } 95 }; 96 struct Deleter { 97 static void call(void *Ptr) { ((ThreadPoolExecutor *)Ptr)->stop(); } 98 }; 99 100 void add(std::function<void()> F, bool Sequential = false) override { 101 { 102 std::lock_guard<std::mutex> Lock(Mutex); 103 if (Sequential) 104 WorkQueueSequential.emplace_front(std::move(F)); 105 else 106 WorkQueue.emplace_back(std::move(F)); 107 } 108 Cond.notify_one(); 109 } 110 111 private: 112 bool hasSequentialTasks() const { 113 return !WorkQueueSequential.empty() && !SequentialQueueIsLocked; 114 } 115 116 bool hasGeneralTasks() const { return !WorkQueue.empty(); } 117 118 void work(ThreadPoolStrategy S, unsigned ThreadID) { 119 threadIndex = ThreadID; 120 S.apply_thread_strategy(ThreadID); 121 while (true) { 122 std::unique_lock<std::mutex> Lock(Mutex); 123 Cond.wait(Lock, [&] { 124 return Stop || hasGeneralTasks() || hasSequentialTasks(); 125 }); 126 if (Stop) 127 break; 128 bool Sequential = hasSequentialTasks(); 129 if (Sequential) 130 SequentialQueueIsLocked = true; 131 else 132 assert(hasGeneralTasks()); 133 134 auto &Queue = Sequential ? WorkQueueSequential : WorkQueue; 135 auto Task = std::move(Queue.back()); 136 Queue.pop_back(); 137 Lock.unlock(); 138 Task(); 139 if (Sequential) 140 SequentialQueueIsLocked = false; 141 } 142 } 143 144 std::atomic<bool> Stop{false}; 145 std::atomic<bool> SequentialQueueIsLocked{false}; 146 std::deque<std::function<void()>> WorkQueue; 147 std::deque<std::function<void()>> WorkQueueSequential; 148 std::mutex Mutex; 149 std::condition_variable Cond; 150 std::promise<void> ThreadsCreated; 151 std::vector<std::thread> Threads; 152 }; 153 154 Executor *Executor::getDefaultExecutor() { 155 // The ManagedStatic enables the ThreadPoolExecutor to be stopped via 156 // llvm_shutdown() which allows a "clean" fast exit, e.g. via _exit(). This 157 // stops the thread pool and waits for any worker thread creation to complete 158 // but does not wait for the threads to finish. The wait for worker thread 159 // creation to complete is important as it prevents intermittent crashes on 160 // Windows due to a race condition between thread creation and process exit. 161 // 162 // The ThreadPoolExecutor will only be destroyed when the static unique_ptr to 163 // it is destroyed, i.e. in a normal full exit. The ThreadPoolExecutor 164 // destructor ensures it has been stopped and waits for worker threads to 165 // finish. The wait is important as it prevents intermittent crashes on 166 // Windows when the process is doing a full exit. 167 // 168 // The Windows crashes appear to only occur with the MSVC static runtimes and 169 // are more frequent with the debug static runtime. 170 // 171 // This also prevents intermittent deadlocks on exit with the MinGW runtime. 172 173 static ManagedStatic<ThreadPoolExecutor, ThreadPoolExecutor::Creator, 174 ThreadPoolExecutor::Deleter> 175 ManagedExec; 176 static std::unique_ptr<ThreadPoolExecutor> Exec(&(*ManagedExec)); 177 return Exec.get(); 178 } 179 } // namespace 180 } // namespace detail 181 #endif 182 183 // Latch::sync() called by the dtor may cause one thread to block. If is a dead 184 // lock if all threads in the default executor are blocked. To prevent the dead 185 // lock, only allow the root TaskGroup to run tasks parallelly. In the scenario 186 // of nested parallel_for_each(), only the outermost one runs parallelly. 187 TaskGroup::TaskGroup() 188 : Parallel((parallel::strategy.ThreadsRequested != 1) && 189 (threadIndex == UINT_MAX)) {} 190 TaskGroup::~TaskGroup() { 191 // We must ensure that all the workloads have finished before decrementing the 192 // instances count. 193 L.sync(); 194 } 195 196 void TaskGroup::spawn(std::function<void()> F, bool Sequential) { 197 #if LLVM_ENABLE_THREADS 198 if (Parallel) { 199 L.inc(); 200 detail::Executor::getDefaultExecutor()->add( 201 [&, F = std::move(F)] { 202 F(); 203 L.dec(); 204 }, 205 Sequential); 206 return; 207 } 208 #endif 209 F(); 210 } 211 212 } // namespace parallel 213 } // namespace llvm 214 215 void llvm::parallelFor(size_t Begin, size_t End, 216 llvm::function_ref<void(size_t)> Fn) { 217 #if LLVM_ENABLE_THREADS 218 if (parallel::strategy.ThreadsRequested != 1) { 219 auto NumItems = End - Begin; 220 // Limit the number of tasks to MaxTasksPerGroup to limit job scheduling 221 // overhead on large inputs. 222 auto TaskSize = NumItems / parallel::detail::MaxTasksPerGroup; 223 if (TaskSize == 0) 224 TaskSize = 1; 225 226 parallel::TaskGroup TG; 227 for (; Begin + TaskSize < End; Begin += TaskSize) { 228 TG.spawn([=, &Fn] { 229 for (size_t I = Begin, E = Begin + TaskSize; I != E; ++I) 230 Fn(I); 231 }); 232 } 233 if (Begin != End) { 234 TG.spawn([=, &Fn] { 235 for (size_t I = Begin; I != End; ++I) 236 Fn(I); 237 }); 238 } 239 return; 240 } 241 #endif 242 243 for (; Begin != End; ++Begin) 244 Fn(Begin); 245 } 246