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"
21 AddTask(std::function<void()>&& task_fn);
27 Worker(TaskPoolImpl* pool);
29 std::queue<std::function<void()>> m_tasks;
30 std::mutex m_tasks_mutex;
31 uint32_t m_thread_count;
34 } // end of anonymous namespace
37 TaskPoolImpl::GetInstance()
39 static TaskPoolImpl g_task_pool_impl;
40 return g_task_pool_impl;
44 TaskPool::AddTaskImpl(std::function<void()>&& task_fn)
46 TaskPoolImpl::GetInstance().AddTask(std::move(task_fn));
49 TaskPoolImpl::TaskPoolImpl() :
55 TaskPoolImpl::AddTask(std::function<void()>&& task_fn)
57 static const uint32_t max_threads = std::thread::hardware_concurrency();
59 std::unique_lock<std::mutex> lock(m_tasks_mutex);
60 m_tasks.emplace(std::move(task_fn));
61 if (m_thread_count < max_threads)
64 // Note that this detach call needs to happen with the m_tasks_mutex held. This prevents the thread
65 // from exiting prematurely and triggering a linux libc bug
66 // (https://sourceware.org/bugzilla/show_bug.cgi?id=19951).
67 std::thread (Worker, this).detach();
72 TaskPoolImpl::Worker(TaskPoolImpl* pool)
76 std::unique_lock<std::mutex> lock(pool->m_tasks_mutex);
77 if (pool->m_tasks.empty())
79 pool->m_thread_count--;
83 std::function<void()> f = pool->m_tasks.front();