16 #include "llvm/Config/llvm-config.h"
21 #if LLVM_ENABLE_THREADS
27 : ActiveThreads(0), EnableFlag(
true) {
30 Threads.reserve(ThreadCount);
31 for (
unsigned ThreadID = 0; ThreadID < ThreadCount; ++ThreadID) {
32 Threads.emplace_back([&] {
36 std::unique_lock<std::mutex> LockGuard(QueueLock);
38 QueueCondition.wait(LockGuard,
39 [&] {
return !EnableFlag || !Tasks.empty(); });
41 if (!EnableFlag && Tasks.empty())
50 std::unique_lock<std::mutex> LockGuard(CompletionLock);
52 Task = std::move(Tasks.front());
64 std::unique_lock<std::mutex> LockGuard(CompletionLock);
69 CompletionCondition.notify_all();
77 std::unique_lock<std::mutex> LockGuard(CompletionLock);
81 CompletionCondition.wait(LockGuard,
82 [&] {
return !ActiveThreads && Tasks.empty(); });
85 std::shared_future<ThreadPool::VoidTy> ThreadPool::asyncImpl(TaskTy Task) {
88 auto Future = PackagedTask.get_future();
91 std::unique_lock<std::mutex> LockGuard(QueueLock);
94 assert(EnableFlag &&
"Queuing a thread during ThreadPool destruction");
96 Tasks.push(std::move(PackagedTask));
98 QueueCondition.notify_one();
99 return Future.share();
105 std::unique_lock<std::mutex> LockGuard(QueueLock);
108 QueueCondition.notify_all();
109 for (
auto &Worker : Threads)
113 #else // LLVM_ENABLE_THREADS Disabled
121 errs() <<
"Warning: request a ThreadPool with " << ThreadCount
122 <<
" threads, but LLVM_ENABLE_THREADS has been turned off\n";
128 while (!Tasks.empty()) {
129 auto Task = std::move(Tasks.front());
139 std::shared_future<ThreadPool::VoidTy> ThreadPool::asyncImpl(TaskTy Task) {
142 auto Future = std::async(std::launch::deferred, std::move(Task)).share();
147 auto Future = std::async(std::launch::deferred, std::move(Task),
false).share();
148 PackagedTaskTy PackagedTask([Future](
bool) ->
bool { Future.get();
return false; });
150 Tasks.push(std::move(PackagedTask));
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
std::packaged_task< void()> PackagedTaskTy
~ThreadPool()
Blocking destructor: the pool will wait for all the threads to complete.
A ThreadPool for asynchronous parallel execution on a defined number of threads.
ThreadPool()
Construct a pool with the number of core available on the system (or whatever the value returned by s...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void wait()
Blocking wait for all the threads to complete and the queue to be empty.