16#include "llvm/Config/llvm-config.h"
36#if LLVM_ENABLE_THREADS
39 : Strategy(S), MaxThreadCount(S.compute_thread_count()) {
40 if (Strategy.UseJobserver)
44void StdThreadPool::grow(
int requested) {
46 if (Threads.size() >= MaxThreadCount)
48 int newThreadCount = std::min<int>(requested, MaxThreadCount);
49 while (
static_cast<int>(Threads.size()) < newThreadCount) {
50 int ThreadID = Threads.size();
51 Threads.emplace_back([
this, ThreadID] {
53 Strategy.apply_thread_strategy(ThreadID);
60 processTasksWithJobserver();
62 processTasks(
nullptr);
70 *CurrentThreadTaskGroups =
nullptr;
79 std::unique_lock<std::mutex> LockGuard(QueueLock);
80 bool workCompletedForGroup =
false;
82 QueueCondition.wait(LockGuard, [&] {
83 return !EnableFlag || !Tasks.empty() ||
84 (WaitingForGroup !=
nullptr &&
85 (workCompletedForGroup =
86 workCompletedUnlocked(WaitingForGroup)));
89 if (!EnableFlag && Tasks.empty())
91 if (WaitingForGroup !=
nullptr && workCompletedForGroup)
99 Task = std::move(Tasks.front().first);
100 GroupOfTask = Tasks.front().second;
103 if (GroupOfTask !=
nullptr)
104 ++ActiveGroups[GroupOfTask];
108 if (CurrentThreadTaskGroups ==
nullptr)
109 CurrentThreadTaskGroups =
new std::vector<ThreadPoolTaskGroup *>;
110 CurrentThreadTaskGroups->push_back(GroupOfTask);
119 std::exchange(Task, {})();
122 CurrentThreadTaskGroups->pop_back();
123 if (CurrentThreadTaskGroups->empty()) {
124 delete CurrentThreadTaskGroups;
125 CurrentThreadTaskGroups =
nullptr;
133 std::lock_guard<std::mutex> LockGuard(QueueLock);
135 if (GroupOfTask !=
nullptr) {
136 auto A = ActiveGroups.find(GroupOfTask);
137 if (--(
A->second) == 0)
138 ActiveGroups.erase(
A);
140 Notify = workCompletedUnlocked(GroupOfTask);
141 NotifyGroup = GroupOfTask !=
nullptr && Notify;
146 CompletionCondition.notify_all();
151 QueueCondition.notify_all();
159void StdThreadPool::processTasksWithJobserver() {
168 bool AcquiredToken =
false;
172 std::unique_lock<std::mutex> LockGuard(QueueLock);
177 Slot = TheJobserver->tryAcquire();
178 if (
Slot.isValid()) {
179 AcquiredToken =
true;
182 }
while (Backoff.waitForNextAttempt());
184 if (!AcquiredToken) {
201 std::unique_lock<std::mutex> LockGuard(QueueLock);
204 QueueCondition.wait(LockGuard,
205 [&] {
return !EnableFlag || !Tasks.empty(); });
208 if (!EnableFlag && Tasks.empty())
219 Task = std::move(Tasks.front().first);
220 GroupOfTask = Tasks.front().second;
221 if (GroupOfTask !=
nullptr)
222 ++ActiveGroups[GroupOfTask];
231 std::lock_guard<std::mutex> LockGuard(QueueLock);
233 if (GroupOfTask !=
nullptr) {
234 auto A = ActiveGroups.find(GroupOfTask);
235 if (--(
A->second) == 0)
236 ActiveGroups.erase(
A);
239 if (workCompletedUnlocked(
nullptr))
240 CompletionCondition.notify_all();
246 if (Group ==
nullptr)
247 return !ActiveThreads && Tasks.empty();
248 return ActiveGroups.count(Group) == 0 &&
252void StdThreadPool::wait() {
253 assert(!isWorkerThread());
255 std::unique_lock<std::mutex> LockGuard(QueueLock);
256 CompletionCondition.wait(LockGuard,
257 [&] {
return workCompletedUnlocked(
nullptr); });
262 if (!isWorkerThread()) {
263 std::unique_lock<std::mutex> LockGuard(QueueLock);
264 CompletionCondition.wait(LockGuard,
265 [&] {
return workCompletedUnlocked(&Group); });
269 assert(CurrentThreadTaskGroups ==
nullptr ||
274 processTasks(&Group);
277bool StdThreadPool::isWorkerThread()
const {
279 llvm::thread::id CurrentThreadId = llvm::this_thread::get_id();
281 if (CurrentThreadId ==
Thread.get_id())
287StdThreadPool::~StdThreadPool() {
289 std::unique_lock<std::mutex> LockGuard(QueueLock);
292 QueueCondition.notify_all();
294 for (
auto &Worker : Threads)
305 <<
" threads, but LLVM_ENABLE_THREADS has been turned off\n";
311 while (!Tasks.empty()) {
312 auto Task = std::move(Tasks.front().first);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_THREAD_LOCAL
\macro LLVM_THREAD_LOCAL A thread-local storage specifier which can be used with globals,...
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.
A JobSlot represents a single job slot that can be acquired from or released to a jobserver pool.
static LLVM_ABI_FOR_TEST JobserverClient * getInstance()
Returns the singleton instance of the JobserverClient.
SingleThreadExecutor(ThreadPoolStrategy ignored={})
Construct a non-threaded pool, ignoring using the hardware strategy.
void wait() override
Blocking wait for all the tasks to execute first.
~SingleThreadExecutor() override
Blocking destructor: the pool will first execute the pending tasks.
bool isWorkerThread() const
Returns true if the current thread is a worker thread of this thread pool.
virtual ~ThreadPoolInterface()
Destroying the pool will drain the pending tasks and wait.
This tells how a thread pool will be used.
LLVM_ABI unsigned compute_thread_count() const
Retrieves the max available threads for the current strategy.
A group of tasks to be run on a thread pool.
unique_function is a type-erasing functor similar to std::function.
SmartScopedWriter< false > ScopedWriter
SmartScopedReader< false > ScopedReader
This is an optimization pass for GlobalISel generic memory operations.
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
LLVM_ABI void set_thread_name(const Twine &Name)
Set the name of the current thread.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.