1 //===--------------------- TaskPool.cpp -------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Utility/TaskPool.h"
15 static TaskPoolImpl &GetInstance();
17 void AddTask(std::function<void()> &&task_fn);
22 static void Worker(TaskPoolImpl *pool);
24 std::queue<std::function<void()>> m_tasks;
25 std::mutex m_tasks_mutex;
26 uint32_t m_thread_count;
29 } // end of anonymous namespace
31 TaskPoolImpl &TaskPoolImpl::GetInstance() {
32 static TaskPoolImpl g_task_pool_impl;
33 return g_task_pool_impl;
36 void TaskPool::AddTaskImpl(std::function<void()> &&task_fn) {
37 TaskPoolImpl::GetInstance().AddTask(std::move(task_fn));
40 TaskPoolImpl::TaskPoolImpl() : m_thread_count(0) {}
42 void TaskPoolImpl::AddTask(std::function<void()> &&task_fn) {
43 static const uint32_t max_threads = std::thread::hardware_concurrency();
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) {
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();
57 void TaskPoolImpl::Worker(TaskPoolImpl *pool) {
59 std::unique_lock<std::mutex> lock(pool->m_tasks_mutex);
60 if (pool->m_tasks.empty()) {
61 pool->m_thread_count--;
65 std::function<void()> f = pool->m_tasks.front();