1 //===-- llvm/Support/ThreadPool.h - 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 defines a crude C++11 based thread pool. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_SUPPORT_THREADPOOL_H 14 #define LLVM_SUPPORT_THREADPOOL_H 15 16 #include "llvm/Config/llvm-config.h" 17 #include "llvm/Support/Threading.h" 18 #include "llvm/Support/thread.h" 19 20 #include <future> 21 22 #include <condition_variable> 23 #include <functional> 24 #include <memory> 25 #include <mutex> 26 #include <queue> 27 #include <utility> 28 29 namespace llvm { 30 31 /// A ThreadPool for asynchronous parallel execution on a defined number of 32 /// threads. 33 /// 34 /// The pool keeps a vector of threads alive, waiting on a condition variable 35 /// for some work to become available. 36 class ThreadPool { 37 public: 38 /// Construct a pool using the hardware strategy \p S for mapping hardware 39 /// execution resources (threads, cores, CPUs) 40 /// Defaults to using the maximum execution resources in the system, but 41 /// accounting for the affinity mask. 42 ThreadPool(ThreadPoolStrategy S = hardware_concurrency()); 43 44 /// Blocking destructor: the pool will wait for all the threads to complete. 45 ~ThreadPool(); 46 47 /// Asynchronous submission of a task to the pool. The returned future can be 48 /// used to wait for the task to finish and is *non-blocking* on destruction. 49 template <typename Function, typename... Args> 50 inline auto async(Function &&F, Args &&...ArgList) { 51 auto Task = 52 std::bind(std::forward<Function>(F), std::forward<Args>(ArgList)...); 53 return async(std::move(Task)); 54 } 55 56 /// Asynchronous submission of a task to the pool. The returned future can be 57 /// used to wait for the task to finish and is *non-blocking* on destruction. 58 template <typename Func> 59 auto async(Func &&F) -> std::shared_future<decltype(F())> { 60 return asyncImpl(std::function<decltype(F())()>(std::forward<Func>(F))); 61 } 62 63 /// Blocking wait for all the threads to complete and the queue to be empty. 64 /// It is an error to try to add new tasks while blocking on this call. 65 void wait(); 66 67 // TODO: misleading legacy name warning! 68 // Returns the maximum number of worker threads in the pool, not the current 69 // number of threads! 70 unsigned getThreadCount() const { return MaxThreadCount; } 71 72 /// Returns true if the current thread is a worker thread of this thread pool. 73 bool isWorkerThread() const; 74 75 private: 76 /// Helpers to create a promise and a callable wrapper of \p Task that sets 77 /// the result of the promise. Returns the callable and a future to access the 78 /// result. 79 template <typename ResTy> 80 static std::pair<std::function<void()>, std::future<ResTy>> 81 createTaskAndFuture(std::function<ResTy()> Task) { 82 std::shared_ptr<std::promise<ResTy>> Promise = 83 std::make_shared<std::promise<ResTy>>(); 84 auto F = Promise->get_future(); 85 return { 86 [Promise = std::move(Promise), Task]() { Promise->set_value(Task()); }, 87 std::move(F)}; 88 } 89 static std::pair<std::function<void()>, std::future<void>> 90 createTaskAndFuture(std::function<void()> Task) { 91 std::shared_ptr<std::promise<void>> Promise = 92 std::make_shared<std::promise<void>>(); 93 auto F = Promise->get_future(); 94 return {[Promise = std::move(Promise), Task]() { 95 Task(); 96 Promise->set_value(); 97 }, 98 std::move(F)}; 99 } 100 101 bool workCompletedUnlocked() { return !ActiveThreads && Tasks.empty(); } 102 103 /// Asynchronous submission of a task to the pool. The returned future can be 104 /// used to wait for the task to finish and is *non-blocking* on destruction. 105 template <typename ResTy> 106 std::shared_future<ResTy> asyncImpl(std::function<ResTy()> Task) { 107 108 #if LLVM_ENABLE_THREADS 109 /// Wrap the Task in a std::function<void()> that sets the result of the 110 /// corresponding future. 111 auto R = createTaskAndFuture(Task); 112 113 int requestedThreads; 114 { 115 // Lock the queue and push the new task 116 std::unique_lock<std::mutex> LockGuard(QueueLock); 117 118 // Don't allow enqueueing after disabling the pool 119 assert(EnableFlag && "Queuing a thread during ThreadPool destruction"); 120 Tasks.push(std::move(R.first)); 121 requestedThreads = ActiveThreads + Tasks.size(); 122 } 123 QueueCondition.notify_one(); 124 grow(requestedThreads); 125 return R.second.share(); 126 127 #else // LLVM_ENABLE_THREADS Disabled 128 129 // Get a Future with launch::deferred execution using std::async 130 auto Future = std::async(std::launch::deferred, std::move(Task)).share(); 131 // Wrap the future so that both ThreadPool::wait() can operate and the 132 // returned future can be sync'ed on. 133 Tasks.push([Future]() { Future.get(); }); 134 return Future; 135 #endif 136 } 137 138 #if LLVM_ENABLE_THREADS 139 // Grow to ensure that we have at least `requested` Threads, but do not go 140 // over MaxThreadCount. 141 void grow(int requested); 142 #endif 143 144 /// Threads in flight 145 std::vector<llvm::thread> Threads; 146 /// Lock protecting access to the Threads vector. 147 mutable std::mutex ThreadsLock; 148 149 /// Tasks waiting for execution in the pool. 150 std::queue<std::function<void()>> Tasks; 151 152 /// Locking and signaling for accessing the Tasks queue. 153 std::mutex QueueLock; 154 std::condition_variable QueueCondition; 155 156 /// Signaling for job completion 157 std::condition_variable CompletionCondition; 158 159 /// Keep track of the number of thread actually busy 160 unsigned ActiveThreads = 0; 161 162 #if LLVM_ENABLE_THREADS // avoids warning for unused variable 163 /// Signal for the destruction of the pool, asking thread to exit. 164 bool EnableFlag = true; 165 #endif 166 167 const ThreadPoolStrategy Strategy; 168 169 /// Maximum number of threads to potentially grow this pool to. 170 const unsigned MaxThreadCount; 171 }; 172 } 173 174 #endif // LLVM_SUPPORT_THREADPOOL_H 175