17d523365SDimitry Andric //==-- llvm/Support/ThreadPool.cpp - A ThreadPool implementation -*- C++ -*-==//
27d523365SDimitry Andric //
37d523365SDimitry Andric //                     The LLVM Compiler Infrastructure
47d523365SDimitry Andric //
57d523365SDimitry Andric // This file is distributed under the University of Illinois Open Source
67d523365SDimitry Andric // License. See LICENSE.TXT for details.
77d523365SDimitry Andric //
87d523365SDimitry Andric //===----------------------------------------------------------------------===//
97d523365SDimitry Andric //
107d523365SDimitry Andric // This file implements a crude C++11 based thread pool.
117d523365SDimitry Andric //
127d523365SDimitry Andric //===----------------------------------------------------------------------===//
137d523365SDimitry Andric 
147d523365SDimitry Andric #include "llvm/Support/ThreadPool.h"
157d523365SDimitry Andric 
167d523365SDimitry Andric #include "llvm/Config/llvm-config.h"
17*2cab237bSDimitry Andric #include "llvm/Support/Threading.h"
187d523365SDimitry Andric #include "llvm/Support/raw_ostream.h"
197d523365SDimitry Andric 
207d523365SDimitry Andric using namespace llvm;
217d523365SDimitry Andric 
227d523365SDimitry Andric #if LLVM_ENABLE_THREADS
237d523365SDimitry Andric 
24*2cab237bSDimitry Andric // Default to hardware_concurrency
ThreadPool()25*2cab237bSDimitry Andric ThreadPool::ThreadPool() : ThreadPool(hardware_concurrency()) {}
267d523365SDimitry Andric 
ThreadPool(unsigned ThreadCount)277d523365SDimitry Andric ThreadPool::ThreadPool(unsigned ThreadCount)
287d523365SDimitry Andric     : ActiveThreads(0), EnableFlag(true) {
297d523365SDimitry Andric   // Create ThreadCount threads that will loop forever, wait on QueueCondition
307d523365SDimitry Andric   // for tasks to be queued or the Pool to be destroyed.
317d523365SDimitry Andric   Threads.reserve(ThreadCount);
327d523365SDimitry Andric   for (unsigned ThreadID = 0; ThreadID < ThreadCount; ++ThreadID) {
337d523365SDimitry Andric     Threads.emplace_back([&] {
347d523365SDimitry Andric       while (true) {
357d523365SDimitry Andric         PackagedTaskTy Task;
367d523365SDimitry Andric         {
377d523365SDimitry Andric           std::unique_lock<std::mutex> LockGuard(QueueLock);
387d523365SDimitry Andric           // Wait for tasks to be pushed in the queue
397d523365SDimitry Andric           QueueCondition.wait(LockGuard,
407d523365SDimitry Andric                               [&] { return !EnableFlag || !Tasks.empty(); });
417d523365SDimitry Andric           // Exit condition
427d523365SDimitry Andric           if (!EnableFlag && Tasks.empty())
437d523365SDimitry Andric             return;
447d523365SDimitry Andric           // Yeah, we have a task, grab it and release the lock on the queue
457d523365SDimitry Andric 
467d523365SDimitry Andric           // We first need to signal that we are active before popping the queue
477d523365SDimitry Andric           // in order for wait() to properly detect that even if the queue is
487d523365SDimitry Andric           // empty, there is still a task in flight.
497d523365SDimitry Andric           {
507d523365SDimitry Andric             std::unique_lock<std::mutex> LockGuard(CompletionLock);
51*2cab237bSDimitry Andric             ++ActiveThreads;
527d523365SDimitry Andric           }
537d523365SDimitry Andric           Task = std::move(Tasks.front());
547d523365SDimitry Andric           Tasks.pop();
557d523365SDimitry Andric         }
567d523365SDimitry Andric         // Run the task we just grabbed
577d523365SDimitry Andric         Task();
587d523365SDimitry Andric 
597d523365SDimitry Andric         {
607d523365SDimitry Andric           // Adjust `ActiveThreads`, in case someone waits on ThreadPool::wait()
617d523365SDimitry Andric           std::unique_lock<std::mutex> LockGuard(CompletionLock);
627d523365SDimitry Andric           --ActiveThreads;
637d523365SDimitry Andric         }
647d523365SDimitry Andric 
657d523365SDimitry Andric         // Notify task completion, in case someone waits on ThreadPool::wait()
667d523365SDimitry Andric         CompletionCondition.notify_all();
677d523365SDimitry Andric       }
687d523365SDimitry Andric     });
697d523365SDimitry Andric   }
707d523365SDimitry Andric }
717d523365SDimitry Andric 
wait()727d523365SDimitry Andric void ThreadPool::wait() {
737d523365SDimitry Andric   // Wait for all threads to complete and the queue to be empty
747d523365SDimitry Andric   std::unique_lock<std::mutex> LockGuard(CompletionLock);
753ca95b02SDimitry Andric   // The order of the checks for ActiveThreads and Tasks.empty() matters because
763ca95b02SDimitry Andric   // any active threads might be modifying the Tasks queue, and this would be a
773ca95b02SDimitry Andric   // race.
787d523365SDimitry Andric   CompletionCondition.wait(LockGuard,
793ca95b02SDimitry Andric                            [&] { return !ActiveThreads && Tasks.empty(); });
807d523365SDimitry Andric }
817d523365SDimitry Andric 
asyncImpl(TaskTy Task)8224d58133SDimitry Andric std::shared_future<void> ThreadPool::asyncImpl(TaskTy Task) {
837d523365SDimitry Andric   /// Wrap the Task in a packaged_task to return a future object.
847d523365SDimitry Andric   PackagedTaskTy PackagedTask(std::move(Task));
857d523365SDimitry Andric   auto Future = PackagedTask.get_future();
867d523365SDimitry Andric   {
877d523365SDimitry Andric     // Lock the queue and push the new task
887d523365SDimitry Andric     std::unique_lock<std::mutex> LockGuard(QueueLock);
897d523365SDimitry Andric 
907d523365SDimitry Andric     // Don't allow enqueueing after disabling the pool
917d523365SDimitry Andric     assert(EnableFlag && "Queuing a thread during ThreadPool destruction");
927d523365SDimitry Andric 
937d523365SDimitry Andric     Tasks.push(std::move(PackagedTask));
947d523365SDimitry Andric   }
957d523365SDimitry Andric   QueueCondition.notify_one();
967d523365SDimitry Andric   return Future.share();
977d523365SDimitry Andric }
987d523365SDimitry Andric 
997d523365SDimitry Andric // The destructor joins all threads, waiting for completion.
~ThreadPool()1007d523365SDimitry Andric ThreadPool::~ThreadPool() {
1017d523365SDimitry Andric   {
1027d523365SDimitry Andric     std::unique_lock<std::mutex> LockGuard(QueueLock);
1037d523365SDimitry Andric     EnableFlag = false;
1047d523365SDimitry Andric   }
1057d523365SDimitry Andric   QueueCondition.notify_all();
1067d523365SDimitry Andric   for (auto &Worker : Threads)
1077d523365SDimitry Andric     Worker.join();
1087d523365SDimitry Andric }
1097d523365SDimitry Andric 
1107d523365SDimitry Andric #else // LLVM_ENABLE_THREADS Disabled
1117d523365SDimitry Andric 
ThreadPool()1127d523365SDimitry Andric ThreadPool::ThreadPool() : ThreadPool(0) {}
1137d523365SDimitry Andric 
1147d523365SDimitry Andric // No threads are launched, issue a warning if ThreadCount is not 0
ThreadPool(unsigned ThreadCount)1157d523365SDimitry Andric ThreadPool::ThreadPool(unsigned ThreadCount)
1167d523365SDimitry Andric     : ActiveThreads(0) {
1177d523365SDimitry Andric   if (ThreadCount) {
1187d523365SDimitry Andric     errs() << "Warning: request a ThreadPool with " << ThreadCount
1197d523365SDimitry Andric            << " threads, but LLVM_ENABLE_THREADS has been turned off\n";
1207d523365SDimitry Andric   }
1217d523365SDimitry Andric }
1227d523365SDimitry Andric 
wait()1237d523365SDimitry Andric void ThreadPool::wait() {
1247d523365SDimitry Andric   // Sequential implementation running the tasks
1257d523365SDimitry Andric   while (!Tasks.empty()) {
1267d523365SDimitry Andric     auto Task = std::move(Tasks.front());
1277d523365SDimitry Andric     Tasks.pop();
1287d523365SDimitry Andric     Task();
1297d523365SDimitry Andric   }
1307d523365SDimitry Andric }
1317d523365SDimitry Andric 
asyncImpl(TaskTy Task)13224d58133SDimitry Andric std::shared_future<void> ThreadPool::asyncImpl(TaskTy Task) {
1337d523365SDimitry Andric   // Get a Future with launch::deferred execution using std::async
1347d523365SDimitry Andric   auto Future = std::async(std::launch::deferred, std::move(Task)).share();
1357d523365SDimitry Andric   // Wrap the future so that both ThreadPool::wait() can operate and the
1367d523365SDimitry Andric   // returned future can be sync'ed on.
1377d523365SDimitry Andric   PackagedTaskTy PackagedTask([Future]() { Future.get(); });
1387d523365SDimitry Andric   Tasks.push(std::move(PackagedTask));
1397d523365SDimitry Andric   return Future;
1407d523365SDimitry Andric }
1417d523365SDimitry Andric 
~ThreadPool()1427d523365SDimitry Andric ThreadPool::~ThreadPool() {
1437d523365SDimitry Andric   wait();
1447d523365SDimitry Andric }
1457d523365SDimitry Andric 
1467d523365SDimitry Andric #endif
147