xref: /src/contrib/llvm-project/llvm/lib/Support/ThreadPool.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1dd58ef01SDimitry Andric //==-- llvm/Support/ThreadPool.cpp - A ThreadPool implementation -*- C++ -*-==//
2dd58ef01SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6dd58ef01SDimitry Andric //
7dd58ef01SDimitry Andric //===----------------------------------------------------------------------===//
8dd58ef01SDimitry Andric //
9dd58ef01SDimitry Andric // This file implements a crude C++11 based thread pool.
10dd58ef01SDimitry Andric //
11dd58ef01SDimitry Andric //===----------------------------------------------------------------------===//
12dd58ef01SDimitry Andric 
13dd58ef01SDimitry Andric #include "llvm/Support/ThreadPool.h"
14dd58ef01SDimitry Andric 
15dd58ef01SDimitry Andric #include "llvm/Config/llvm-config.h"
166f8fc217SDimitry Andric 
177fa27ce4SDimitry Andric #include "llvm/Support/FormatVariadic.h"
18044eb2f6SDimitry Andric #include "llvm/Support/Threading.h"
19dd58ef01SDimitry Andric #include "llvm/Support/raw_ostream.h"
20dd58ef01SDimitry Andric 
21dd58ef01SDimitry Andric using namespace llvm;
22dd58ef01SDimitry Andric 
23ac9a064cSDimitry Andric ThreadPoolInterface::~ThreadPoolInterface() = default;
24dd58ef01SDimitry Andric 
25145449b1SDimitry Andric // A note on thread groups: Tasks are by default in no group (represented
26145449b1SDimitry Andric // by nullptr ThreadPoolTaskGroup pointer in the Tasks queue) and functionality
27145449b1SDimitry Andric // here normally works on all tasks regardless of their group (functions
28145449b1SDimitry Andric // in that case receive nullptr ThreadPoolTaskGroup pointer as argument).
29145449b1SDimitry Andric // A task in a group has a pointer to that ThreadPoolTaskGroup in the Tasks
30145449b1SDimitry Andric // queue, and functions called to work only on tasks from one group take that
31145449b1SDimitry Andric // pointer.
32145449b1SDimitry Andric 
33ac9a064cSDimitry Andric #if LLVM_ENABLE_THREADS
34ac9a064cSDimitry Andric 
StdThreadPool(ThreadPoolStrategy S)35ac9a064cSDimitry Andric StdThreadPool::StdThreadPool(ThreadPoolStrategy S)
3677fc4c14SDimitry Andric     : Strategy(S), MaxThreadCount(S.compute_thread_count()) {}
3777fc4c14SDimitry Andric 
grow(int requested)38ac9a064cSDimitry Andric void StdThreadPool::grow(int requested) {
39145449b1SDimitry Andric   llvm::sys::ScopedWriter LockGuard(ThreadsLock);
4077fc4c14SDimitry Andric   if (Threads.size() >= MaxThreadCount)
4177fc4c14SDimitry Andric     return; // Already hit the max thread pool size.
4277fc4c14SDimitry Andric   int newThreadCount = std::min<int>(requested, MaxThreadCount);
4377fc4c14SDimitry Andric   while (static_cast<int>(Threads.size()) < newThreadCount) {
4477fc4c14SDimitry Andric     int ThreadID = Threads.size();
4577fc4c14SDimitry Andric     Threads.emplace_back([this, ThreadID] {
467fa27ce4SDimitry Andric       set_thread_name(formatv("llvm-worker-{0}", ThreadID));
4777fc4c14SDimitry Andric       Strategy.apply_thread_strategy(ThreadID);
48145449b1SDimitry Andric       processTasks(nullptr);
49145449b1SDimitry Andric     });
50145449b1SDimitry Andric   }
51145449b1SDimitry Andric }
52145449b1SDimitry Andric 
53145449b1SDimitry Andric #ifndef NDEBUG
54145449b1SDimitry Andric // The group of the tasks run by the current thread.
55145449b1SDimitry Andric static LLVM_THREAD_LOCAL std::vector<ThreadPoolTaskGroup *>
56145449b1SDimitry Andric     *CurrentThreadTaskGroups = nullptr;
57145449b1SDimitry Andric #endif
58145449b1SDimitry Andric 
59145449b1SDimitry Andric // WaitingForGroup == nullptr means all tasks regardless of their group.
processTasks(ThreadPoolTaskGroup * WaitingForGroup)60ac9a064cSDimitry Andric void StdThreadPool::processTasks(ThreadPoolTaskGroup *WaitingForGroup) {
61dd58ef01SDimitry Andric   while (true) {
62f65dcba8SDimitry Andric     std::function<void()> Task;
63145449b1SDimitry Andric     ThreadPoolTaskGroup *GroupOfTask;
64dd58ef01SDimitry Andric     {
65dd58ef01SDimitry Andric       std::unique_lock<std::mutex> LockGuard(QueueLock);
66145449b1SDimitry Andric       bool workCompletedForGroup = false; // Result of workCompletedUnlocked()
67dd58ef01SDimitry Andric       // Wait for tasks to be pushed in the queue
68145449b1SDimitry Andric       QueueCondition.wait(LockGuard, [&] {
69145449b1SDimitry Andric         return !EnableFlag || !Tasks.empty() ||
70145449b1SDimitry Andric                (WaitingForGroup != nullptr &&
71145449b1SDimitry Andric                 (workCompletedForGroup =
72145449b1SDimitry Andric                      workCompletedUnlocked(WaitingForGroup)));
73145449b1SDimitry Andric       });
74dd58ef01SDimitry Andric       // Exit condition
75dd58ef01SDimitry Andric       if (!EnableFlag && Tasks.empty())
76dd58ef01SDimitry Andric         return;
77145449b1SDimitry Andric       if (WaitingForGroup != nullptr && workCompletedForGroup)
78145449b1SDimitry Andric         return;
79dd58ef01SDimitry Andric       // Yeah, we have a task, grab it and release the lock on the queue
80dd58ef01SDimitry Andric 
81dd58ef01SDimitry Andric       // We first need to signal that we are active before popping the queue
82dd58ef01SDimitry Andric       // in order for wait() to properly detect that even if the queue is
83dd58ef01SDimitry Andric       // empty, there is still a task in flight.
84044eb2f6SDimitry Andric       ++ActiveThreads;
85145449b1SDimitry Andric       Task = std::move(Tasks.front().first);
86145449b1SDimitry Andric       GroupOfTask = Tasks.front().second;
87145449b1SDimitry Andric       // Need to count active threads in each group separately, ActiveThreads
88145449b1SDimitry Andric       // would never be 0 if waiting for another group inside a wait.
89145449b1SDimitry Andric       if (GroupOfTask != nullptr)
90145449b1SDimitry Andric         ++ActiveGroups[GroupOfTask]; // Increment or set to 1 if new item
91145449b1SDimitry Andric       Tasks.pop_front();
92dd58ef01SDimitry Andric     }
93145449b1SDimitry Andric #ifndef NDEBUG
94145449b1SDimitry Andric     if (CurrentThreadTaskGroups == nullptr)
95145449b1SDimitry Andric       CurrentThreadTaskGroups = new std::vector<ThreadPoolTaskGroup *>;
96145449b1SDimitry Andric     CurrentThreadTaskGroups->push_back(GroupOfTask);
97145449b1SDimitry Andric #endif
98145449b1SDimitry Andric 
99dd58ef01SDimitry Andric     // Run the task we just grabbed
100dd58ef01SDimitry Andric     Task();
101dd58ef01SDimitry Andric 
102145449b1SDimitry Andric #ifndef NDEBUG
103145449b1SDimitry Andric     CurrentThreadTaskGroups->pop_back();
104145449b1SDimitry Andric     if (CurrentThreadTaskGroups->empty()) {
105145449b1SDimitry Andric       delete CurrentThreadTaskGroups;
106145449b1SDimitry Andric       CurrentThreadTaskGroups = nullptr;
107145449b1SDimitry Andric     }
108145449b1SDimitry Andric #endif
109145449b1SDimitry Andric 
110cfca06d7SDimitry Andric     bool Notify;
111145449b1SDimitry Andric     bool NotifyGroup;
112dd58ef01SDimitry Andric     {
113ac9a064cSDimitry Andric       // Adjust `ActiveThreads`, in case someone waits on StdThreadPool::wait()
114cfca06d7SDimitry Andric       std::lock_guard<std::mutex> LockGuard(QueueLock);
115dd58ef01SDimitry Andric       --ActiveThreads;
116145449b1SDimitry Andric       if (GroupOfTask != nullptr) {
117145449b1SDimitry Andric         auto A = ActiveGroups.find(GroupOfTask);
118145449b1SDimitry Andric         if (--(A->second) == 0)
119145449b1SDimitry Andric           ActiveGroups.erase(A);
120145449b1SDimitry Andric       }
121145449b1SDimitry Andric       Notify = workCompletedUnlocked(GroupOfTask);
122145449b1SDimitry Andric       NotifyGroup = GroupOfTask != nullptr && Notify;
123dd58ef01SDimitry Andric     }
124cfca06d7SDimitry Andric     // Notify task completion if this is the last active thread, in case
125ac9a064cSDimitry Andric     // someone waits on StdThreadPool::wait().
126cfca06d7SDimitry Andric     if (Notify)
127dd58ef01SDimitry Andric       CompletionCondition.notify_all();
128145449b1SDimitry Andric     // If this was a task in a group, notify also threads waiting for tasks
129145449b1SDimitry Andric     // in this function on QueueCondition, to make a recursive wait() return
130145449b1SDimitry Andric     // after the group it's been waiting for has finished.
131145449b1SDimitry Andric     if (NotifyGroup)
132145449b1SDimitry Andric       QueueCondition.notify_all();
133dd58ef01SDimitry Andric   }
134dd58ef01SDimitry Andric }
135145449b1SDimitry Andric 
workCompletedUnlocked(ThreadPoolTaskGroup * Group) const136ac9a064cSDimitry Andric bool StdThreadPool::workCompletedUnlocked(ThreadPoolTaskGroup *Group) const {
137145449b1SDimitry Andric   if (Group == nullptr)
138145449b1SDimitry Andric     return !ActiveThreads && Tasks.empty();
139145449b1SDimitry Andric   return ActiveGroups.count(Group) == 0 &&
140145449b1SDimitry Andric          !llvm::any_of(Tasks,
141145449b1SDimitry Andric                        [Group](const auto &T) { return T.second == Group; });
142dd58ef01SDimitry Andric }
143dd58ef01SDimitry Andric 
wait()144ac9a064cSDimitry Andric void StdThreadPool::wait() {
145145449b1SDimitry Andric   assert(!isWorkerThread()); // Would deadlock waiting for itself.
146dd58ef01SDimitry Andric   // Wait for all threads to complete and the queue to be empty
147cfca06d7SDimitry Andric   std::unique_lock<std::mutex> LockGuard(QueueLock);
148145449b1SDimitry Andric   CompletionCondition.wait(LockGuard,
149145449b1SDimitry Andric                            [&] { return workCompletedUnlocked(nullptr); });
150145449b1SDimitry Andric }
151145449b1SDimitry Andric 
wait(ThreadPoolTaskGroup & Group)152ac9a064cSDimitry Andric void StdThreadPool::wait(ThreadPoolTaskGroup &Group) {
153145449b1SDimitry Andric   // Wait for all threads in the group to complete.
154145449b1SDimitry Andric   if (!isWorkerThread()) {
155145449b1SDimitry Andric     std::unique_lock<std::mutex> LockGuard(QueueLock);
156145449b1SDimitry Andric     CompletionCondition.wait(LockGuard,
157145449b1SDimitry Andric                              [&] { return workCompletedUnlocked(&Group); });
158145449b1SDimitry Andric     return;
159145449b1SDimitry Andric   }
160145449b1SDimitry Andric   // Make sure to not deadlock waiting for oneself.
161145449b1SDimitry Andric   assert(CurrentThreadTaskGroups == nullptr ||
162145449b1SDimitry Andric          !llvm::is_contained(*CurrentThreadTaskGroups, &Group));
163145449b1SDimitry Andric   // Handle the case of recursive call from another task in a different group,
164145449b1SDimitry Andric   // in which case process tasks while waiting to keep the thread busy and avoid
165145449b1SDimitry Andric   // possible deadlock.
166145449b1SDimitry Andric   processTasks(&Group);
167dd58ef01SDimitry Andric }
168dd58ef01SDimitry Andric 
isWorkerThread() const169ac9a064cSDimitry Andric bool StdThreadPool::isWorkerThread() const {
170145449b1SDimitry Andric   llvm::sys::ScopedReader LockGuard(ThreadsLock);
171344a3780SDimitry Andric   llvm::thread::id CurrentThreadId = llvm::this_thread::get_id();
172344a3780SDimitry Andric   for (const llvm::thread &Thread : Threads)
173344a3780SDimitry Andric     if (CurrentThreadId == Thread.get_id())
174344a3780SDimitry Andric       return true;
175344a3780SDimitry Andric   return false;
176344a3780SDimitry Andric }
177344a3780SDimitry Andric 
178dd58ef01SDimitry Andric // The destructor joins all threads, waiting for completion.
~StdThreadPool()179ac9a064cSDimitry Andric StdThreadPool::~StdThreadPool() {
180dd58ef01SDimitry Andric   {
181dd58ef01SDimitry Andric     std::unique_lock<std::mutex> LockGuard(QueueLock);
182dd58ef01SDimitry Andric     EnableFlag = false;
183dd58ef01SDimitry Andric   }
184dd58ef01SDimitry Andric   QueueCondition.notify_all();
185145449b1SDimitry Andric   llvm::sys::ScopedReader LockGuard(ThreadsLock);
186dd58ef01SDimitry Andric   for (auto &Worker : Threads)
187dd58ef01SDimitry Andric     Worker.join();
188dd58ef01SDimitry Andric }
189dd58ef01SDimitry Andric 
190ac9a064cSDimitry Andric #endif // LLVM_ENABLE_THREADS Disabled
191dd58ef01SDimitry Andric 
192dd58ef01SDimitry Andric // No threads are launched, issue a warning if ThreadCount is not 0
SingleThreadExecutor(ThreadPoolStrategy S)193ac9a064cSDimitry Andric SingleThreadExecutor::SingleThreadExecutor(ThreadPoolStrategy S) {
19477fc4c14SDimitry Andric   int ThreadCount = S.compute_thread_count();
195cfca06d7SDimitry Andric   if (ThreadCount != 1) {
196dd58ef01SDimitry Andric     errs() << "Warning: request a ThreadPool with " << ThreadCount
197dd58ef01SDimitry Andric            << " threads, but LLVM_ENABLE_THREADS has been turned off\n";
198dd58ef01SDimitry Andric   }
199dd58ef01SDimitry Andric }
200dd58ef01SDimitry Andric 
wait()201ac9a064cSDimitry Andric void SingleThreadExecutor::wait() {
202dd58ef01SDimitry Andric   // Sequential implementation running the tasks
203dd58ef01SDimitry Andric   while (!Tasks.empty()) {
204145449b1SDimitry Andric     auto Task = std::move(Tasks.front().first);
205145449b1SDimitry Andric     Tasks.pop_front();
206dd58ef01SDimitry Andric     Task();
207dd58ef01SDimitry Andric   }
208dd58ef01SDimitry Andric }
209dd58ef01SDimitry Andric 
wait(ThreadPoolTaskGroup &)210ac9a064cSDimitry Andric void SingleThreadExecutor::wait(ThreadPoolTaskGroup &) {
211145449b1SDimitry Andric   // Simply wait for all, this works even if recursive (the running task
212145449b1SDimitry Andric   // is already removed from the queue).
213145449b1SDimitry Andric   wait();
214145449b1SDimitry Andric }
215145449b1SDimitry Andric 
isWorkerThread() const216ac9a064cSDimitry Andric bool SingleThreadExecutor::isWorkerThread() const {
2176f8fc217SDimitry Andric   report_fatal_error("LLVM compiled without multithreading");
2186f8fc217SDimitry Andric }
2196f8fc217SDimitry Andric 
~SingleThreadExecutor()220ac9a064cSDimitry Andric SingleThreadExecutor::~SingleThreadExecutor() { wait(); }
221