10b57cec5SDimitry Andric //==-- llvm/Support/ThreadPool.cpp - A ThreadPool implementation -*- C++ -*-==//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements a crude C++11 based thread pool.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric
130b57cec5SDimitry Andric #include "llvm/Support/ThreadPool.h"
140b57cec5SDimitry Andric
150b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
1604eeddc0SDimitry Andric
1704eeddc0SDimitry Andric #if LLVM_ENABLE_THREADS
18*fe013be4SDimitry Andric #include "llvm/Support/FormatVariadic.h"
190b57cec5SDimitry Andric #include "llvm/Support/Threading.h"
2004eeddc0SDimitry Andric #else
210b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
2204eeddc0SDimitry Andric #endif
230b57cec5SDimitry Andric
240b57cec5SDimitry Andric using namespace llvm;
250b57cec5SDimitry Andric
260b57cec5SDimitry Andric #if LLVM_ENABLE_THREADS
270b57cec5SDimitry Andric
2881ad6265SDimitry Andric // A note on thread groups: Tasks are by default in no group (represented
2981ad6265SDimitry Andric // by nullptr ThreadPoolTaskGroup pointer in the Tasks queue) and functionality
3081ad6265SDimitry Andric // here normally works on all tasks regardless of their group (functions
3181ad6265SDimitry Andric // in that case receive nullptr ThreadPoolTaskGroup pointer as argument).
3281ad6265SDimitry Andric // A task in a group has a pointer to that ThreadPoolTaskGroup in the Tasks
3381ad6265SDimitry Andric // queue, and functions called to work only on tasks from one group take that
3481ad6265SDimitry Andric // pointer.
3581ad6265SDimitry Andric
ThreadPool(ThreadPoolStrategy S)365ffd83dbSDimitry Andric ThreadPool::ThreadPool(ThreadPoolStrategy S)
370eae32dcSDimitry Andric : Strategy(S), MaxThreadCount(S.compute_thread_count()) {}
380eae32dcSDimitry Andric
grow(int requested)390eae32dcSDimitry Andric void ThreadPool::grow(int requested) {
4081ad6265SDimitry Andric llvm::sys::ScopedWriter LockGuard(ThreadsLock);
410eae32dcSDimitry Andric if (Threads.size() >= MaxThreadCount)
420eae32dcSDimitry Andric return; // Already hit the max thread pool size.
430eae32dcSDimitry Andric int newThreadCount = std::min<int>(requested, MaxThreadCount);
440eae32dcSDimitry Andric while (static_cast<int>(Threads.size()) < newThreadCount) {
450eae32dcSDimitry Andric int ThreadID = Threads.size();
460eae32dcSDimitry Andric Threads.emplace_back([this, ThreadID] {
47*fe013be4SDimitry Andric set_thread_name(formatv("llvm-worker-{0}", ThreadID));
480eae32dcSDimitry Andric Strategy.apply_thread_strategy(ThreadID);
4981ad6265SDimitry Andric processTasks(nullptr);
5081ad6265SDimitry Andric });
5181ad6265SDimitry Andric }
5281ad6265SDimitry Andric }
5381ad6265SDimitry Andric
5481ad6265SDimitry Andric #ifndef NDEBUG
5581ad6265SDimitry Andric // The group of the tasks run by the current thread.
5681ad6265SDimitry Andric static LLVM_THREAD_LOCAL std::vector<ThreadPoolTaskGroup *>
5781ad6265SDimitry Andric *CurrentThreadTaskGroups = nullptr;
5881ad6265SDimitry Andric #endif
5981ad6265SDimitry Andric
6081ad6265SDimitry Andric // WaitingForGroup == nullptr means all tasks regardless of their group.
processTasks(ThreadPoolTaskGroup * WaitingForGroup)6181ad6265SDimitry Andric void ThreadPool::processTasks(ThreadPoolTaskGroup *WaitingForGroup) {
620b57cec5SDimitry Andric while (true) {
634824e7fdSDimitry Andric std::function<void()> Task;
6481ad6265SDimitry Andric ThreadPoolTaskGroup *GroupOfTask;
650b57cec5SDimitry Andric {
660b57cec5SDimitry Andric std::unique_lock<std::mutex> LockGuard(QueueLock);
6781ad6265SDimitry Andric bool workCompletedForGroup = false; // Result of workCompletedUnlocked()
680b57cec5SDimitry Andric // Wait for tasks to be pushed in the queue
6981ad6265SDimitry Andric QueueCondition.wait(LockGuard, [&] {
7081ad6265SDimitry Andric return !EnableFlag || !Tasks.empty() ||
7181ad6265SDimitry Andric (WaitingForGroup != nullptr &&
7281ad6265SDimitry Andric (workCompletedForGroup =
7381ad6265SDimitry Andric workCompletedUnlocked(WaitingForGroup)));
7481ad6265SDimitry Andric });
750b57cec5SDimitry Andric // Exit condition
760b57cec5SDimitry Andric if (!EnableFlag && Tasks.empty())
770b57cec5SDimitry Andric return;
7881ad6265SDimitry Andric if (WaitingForGroup != nullptr && workCompletedForGroup)
7981ad6265SDimitry Andric return;
800b57cec5SDimitry Andric // Yeah, we have a task, grab it and release the lock on the queue
810b57cec5SDimitry Andric
820b57cec5SDimitry Andric // We first need to signal that we are active before popping the queue
830b57cec5SDimitry Andric // in order for wait() to properly detect that even if the queue is
840b57cec5SDimitry Andric // empty, there is still a task in flight.
850b57cec5SDimitry Andric ++ActiveThreads;
8681ad6265SDimitry Andric Task = std::move(Tasks.front().first);
8781ad6265SDimitry Andric GroupOfTask = Tasks.front().second;
8881ad6265SDimitry Andric // Need to count active threads in each group separately, ActiveThreads
8981ad6265SDimitry Andric // would never be 0 if waiting for another group inside a wait.
9081ad6265SDimitry Andric if (GroupOfTask != nullptr)
9181ad6265SDimitry Andric ++ActiveGroups[GroupOfTask]; // Increment or set to 1 if new item
9281ad6265SDimitry Andric Tasks.pop_front();
930b57cec5SDimitry Andric }
9481ad6265SDimitry Andric #ifndef NDEBUG
9581ad6265SDimitry Andric if (CurrentThreadTaskGroups == nullptr)
9681ad6265SDimitry Andric CurrentThreadTaskGroups = new std::vector<ThreadPoolTaskGroup *>;
9781ad6265SDimitry Andric CurrentThreadTaskGroups->push_back(GroupOfTask);
9881ad6265SDimitry Andric #endif
9981ad6265SDimitry Andric
1000b57cec5SDimitry Andric // Run the task we just grabbed
1010b57cec5SDimitry Andric Task();
1020b57cec5SDimitry Andric
10381ad6265SDimitry Andric #ifndef NDEBUG
10481ad6265SDimitry Andric CurrentThreadTaskGroups->pop_back();
10581ad6265SDimitry Andric if (CurrentThreadTaskGroups->empty()) {
10681ad6265SDimitry Andric delete CurrentThreadTaskGroups;
10781ad6265SDimitry Andric CurrentThreadTaskGroups = nullptr;
10881ad6265SDimitry Andric }
10981ad6265SDimitry Andric #endif
11081ad6265SDimitry Andric
1115ffd83dbSDimitry Andric bool Notify;
11281ad6265SDimitry Andric bool NotifyGroup;
1130b57cec5SDimitry Andric {
1140b57cec5SDimitry Andric // Adjust `ActiveThreads`, in case someone waits on ThreadPool::wait()
1155ffd83dbSDimitry Andric std::lock_guard<std::mutex> LockGuard(QueueLock);
1160b57cec5SDimitry Andric --ActiveThreads;
11781ad6265SDimitry Andric if (GroupOfTask != nullptr) {
11881ad6265SDimitry Andric auto A = ActiveGroups.find(GroupOfTask);
11981ad6265SDimitry Andric if (--(A->second) == 0)
12081ad6265SDimitry Andric ActiveGroups.erase(A);
12181ad6265SDimitry Andric }
12281ad6265SDimitry Andric Notify = workCompletedUnlocked(GroupOfTask);
12381ad6265SDimitry Andric NotifyGroup = GroupOfTask != nullptr && Notify;
1240b57cec5SDimitry Andric }
1255ffd83dbSDimitry Andric // Notify task completion if this is the last active thread, in case
1265ffd83dbSDimitry Andric // someone waits on ThreadPool::wait().
1275ffd83dbSDimitry Andric if (Notify)
1280b57cec5SDimitry Andric CompletionCondition.notify_all();
12981ad6265SDimitry Andric // If this was a task in a group, notify also threads waiting for tasks
13081ad6265SDimitry Andric // in this function on QueueCondition, to make a recursive wait() return
13181ad6265SDimitry Andric // after the group it's been waiting for has finished.
13281ad6265SDimitry Andric if (NotifyGroup)
13381ad6265SDimitry Andric QueueCondition.notify_all();
1340b57cec5SDimitry Andric }
1350b57cec5SDimitry Andric }
13681ad6265SDimitry Andric
workCompletedUnlocked(ThreadPoolTaskGroup * Group) const13781ad6265SDimitry Andric bool ThreadPool::workCompletedUnlocked(ThreadPoolTaskGroup *Group) const {
13881ad6265SDimitry Andric if (Group == nullptr)
13981ad6265SDimitry Andric return !ActiveThreads && Tasks.empty();
14081ad6265SDimitry Andric return ActiveGroups.count(Group) == 0 &&
14181ad6265SDimitry Andric !llvm::any_of(Tasks,
14281ad6265SDimitry Andric [Group](const auto &T) { return T.second == Group; });
1430b57cec5SDimitry Andric }
1440b57cec5SDimitry Andric
wait()1450b57cec5SDimitry Andric void ThreadPool::wait() {
14681ad6265SDimitry Andric assert(!isWorkerThread()); // Would deadlock waiting for itself.
1470b57cec5SDimitry Andric // Wait for all threads to complete and the queue to be empty
1485ffd83dbSDimitry Andric std::unique_lock<std::mutex> LockGuard(QueueLock);
14981ad6265SDimitry Andric CompletionCondition.wait(LockGuard,
15081ad6265SDimitry Andric [&] { return workCompletedUnlocked(nullptr); });
15181ad6265SDimitry Andric }
15281ad6265SDimitry Andric
wait(ThreadPoolTaskGroup & Group)15381ad6265SDimitry Andric void ThreadPool::wait(ThreadPoolTaskGroup &Group) {
15481ad6265SDimitry Andric // Wait for all threads in the group to complete.
15581ad6265SDimitry Andric if (!isWorkerThread()) {
15681ad6265SDimitry Andric std::unique_lock<std::mutex> LockGuard(QueueLock);
15781ad6265SDimitry Andric CompletionCondition.wait(LockGuard,
15881ad6265SDimitry Andric [&] { return workCompletedUnlocked(&Group); });
15981ad6265SDimitry Andric return;
16081ad6265SDimitry Andric }
16181ad6265SDimitry Andric // Make sure to not deadlock waiting for oneself.
16281ad6265SDimitry Andric assert(CurrentThreadTaskGroups == nullptr ||
16381ad6265SDimitry Andric !llvm::is_contained(*CurrentThreadTaskGroups, &Group));
16481ad6265SDimitry Andric // Handle the case of recursive call from another task in a different group,
16581ad6265SDimitry Andric // in which case process tasks while waiting to keep the thread busy and avoid
16681ad6265SDimitry Andric // possible deadlock.
16781ad6265SDimitry Andric processTasks(&Group);
1680b57cec5SDimitry Andric }
1690b57cec5SDimitry Andric
isWorkerThread() const170fe6060f1SDimitry Andric bool ThreadPool::isWorkerThread() const {
17181ad6265SDimitry Andric llvm::sys::ScopedReader LockGuard(ThreadsLock);
172fe6060f1SDimitry Andric llvm::thread::id CurrentThreadId = llvm::this_thread::get_id();
173fe6060f1SDimitry Andric for (const llvm::thread &Thread : Threads)
174fe6060f1SDimitry Andric if (CurrentThreadId == Thread.get_id())
175fe6060f1SDimitry Andric return true;
176fe6060f1SDimitry Andric return false;
177fe6060f1SDimitry Andric }
178fe6060f1SDimitry Andric
1790b57cec5SDimitry Andric // The destructor joins all threads, waiting for completion.
~ThreadPool()1800b57cec5SDimitry Andric ThreadPool::~ThreadPool() {
1810b57cec5SDimitry Andric {
1820b57cec5SDimitry Andric std::unique_lock<std::mutex> LockGuard(QueueLock);
1830b57cec5SDimitry Andric EnableFlag = false;
1840b57cec5SDimitry Andric }
1850b57cec5SDimitry Andric QueueCondition.notify_all();
18681ad6265SDimitry Andric llvm::sys::ScopedReader LockGuard(ThreadsLock);
1870b57cec5SDimitry Andric for (auto &Worker : Threads)
1880b57cec5SDimitry Andric Worker.join();
1890b57cec5SDimitry Andric }
1900b57cec5SDimitry Andric
1910b57cec5SDimitry Andric #else // LLVM_ENABLE_THREADS Disabled
1920b57cec5SDimitry Andric
1930b57cec5SDimitry Andric // No threads are launched, issue a warning if ThreadCount is not 0
ThreadPool(ThreadPoolStrategy S)1940eae32dcSDimitry Andric ThreadPool::ThreadPool(ThreadPoolStrategy S) : MaxThreadCount(1) {
1950eae32dcSDimitry Andric int ThreadCount = S.compute_thread_count();
1965ffd83dbSDimitry Andric if (ThreadCount != 1) {
1970b57cec5SDimitry Andric errs() << "Warning: request a ThreadPool with " << ThreadCount
1980b57cec5SDimitry Andric << " threads, but LLVM_ENABLE_THREADS has been turned off\n";
1990b57cec5SDimitry Andric }
2000b57cec5SDimitry Andric }
2010b57cec5SDimitry Andric
wait()2020b57cec5SDimitry Andric void ThreadPool::wait() {
2030b57cec5SDimitry Andric // Sequential implementation running the tasks
2040b57cec5SDimitry Andric while (!Tasks.empty()) {
20581ad6265SDimitry Andric auto Task = std::move(Tasks.front().first);
20681ad6265SDimitry Andric Tasks.pop_front();
2070b57cec5SDimitry Andric Task();
2080b57cec5SDimitry Andric }
2090b57cec5SDimitry Andric }
2100b57cec5SDimitry Andric
wait(ThreadPoolTaskGroup &)21181ad6265SDimitry Andric void ThreadPool::wait(ThreadPoolTaskGroup &) {
21281ad6265SDimitry Andric // Simply wait for all, this works even if recursive (the running task
21381ad6265SDimitry Andric // is already removed from the queue).
21481ad6265SDimitry Andric wait();
21581ad6265SDimitry Andric }
21681ad6265SDimitry Andric
isWorkerThread() const21704eeddc0SDimitry Andric bool ThreadPool::isWorkerThread() const {
21804eeddc0SDimitry Andric report_fatal_error("LLVM compiled without multithreading");
21904eeddc0SDimitry Andric }
22004eeddc0SDimitry Andric
~ThreadPool()2215ffd83dbSDimitry Andric ThreadPool::~ThreadPool() { wait(); }
2220b57cec5SDimitry Andric
2230b57cec5SDimitry Andric #endif
224