]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - source/Utility/TaskPool.cpp
Vendor import of lldb trunk r290819:
[FreeBSD/FreeBSD.git] / source / Utility / TaskPool.cpp
1 //===--------------------- TaskPool.cpp -------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "lldb/Utility/TaskPool.h"
11
12 namespace {
13 class TaskPoolImpl {
14 public:
15   static TaskPoolImpl &GetInstance();
16
17   void AddTask(std::function<void()> &&task_fn);
18
19 private:
20   TaskPoolImpl();
21
22   static void Worker(TaskPoolImpl *pool);
23
24   std::queue<std::function<void()>> m_tasks;
25   std::mutex m_tasks_mutex;
26   uint32_t m_thread_count;
27 };
28
29 } // end of anonymous namespace
30
31 TaskPoolImpl &TaskPoolImpl::GetInstance() {
32   static TaskPoolImpl g_task_pool_impl;
33   return g_task_pool_impl;
34 }
35
36 void TaskPool::AddTaskImpl(std::function<void()> &&task_fn) {
37   TaskPoolImpl::GetInstance().AddTask(std::move(task_fn));
38 }
39
40 TaskPoolImpl::TaskPoolImpl() : m_thread_count(0) {}
41
42 void TaskPoolImpl::AddTask(std::function<void()> &&task_fn) {
43   static const uint32_t max_threads = std::thread::hardware_concurrency();
44
45   std::unique_lock<std::mutex> lock(m_tasks_mutex);
46   m_tasks.emplace(std::move(task_fn));
47   if (m_thread_count < max_threads) {
48     m_thread_count++;
49     // Note that this detach call needs to happen with the m_tasks_mutex held.
50     // This prevents the thread
51     // from exiting prematurely and triggering a linux libc bug
52     // (https://sourceware.org/bugzilla/show_bug.cgi?id=19951).
53     std::thread(Worker, this).detach();
54   }
55 }
56
57 void TaskPoolImpl::Worker(TaskPoolImpl *pool) {
58   while (true) {
59     std::unique_lock<std::mutex> lock(pool->m_tasks_mutex);
60     if (pool->m_tasks.empty()) {
61       pool->m_thread_count--;
62       break;
63     }
64
65     std::function<void()> f = pool->m_tasks.front();
66     pool->m_tasks.pop();
67     lock.unlock();
68
69     f();
70   }
71 }