22#include "threadpool.h"
26#define WTH_KEEPALIVE 5000
29using namespace NSROOT::OS;
34ThreadPool::ThreadPool()
36, m_keepAlive(WTH_KEEPALIVE)
45ThreadPool::ThreadPool(
unsigned size)
47, m_keepAlive(WTH_KEEPALIVE)
56ThreadPool::~ThreadPool()
62 while (!m_queue.empty())
64 delete m_queue.front();
72 for (std::set<WorkerThread*>::iterator it = m_pool.begin(); it != m_pool.end(); ++it)
73 (*it)->stop_thread(
false);
75 m_queueFill.notify_all();
77 m_condition.wait(m_mutex, m_empty);
81bool ThreadPool::enqueue(Worker* worker)
83 assert(worker->m_queued !=
true);
84 LockGuard lock(m_mutex);
87 worker->m_queued =
true;
94 m_queueFill.notify_one();
109void ThreadPool::set_max_size(
unsigned size)
111 LockGuard lock(m_mutex);
117void ThreadPool::set_keep_alive(
unsigned millisec)
119 LockGuard lock(m_mutex);
120 m_keepAlive = millisec;
123unsigned ThreadPool::size()
const
125 LockGuard lock(m_mutex);
129unsigned ThreadPool::queue_size()
const
131 LockGuard lock(m_mutex);
132 return static_cast<unsigned>(m_queue.size());
135bool ThreadPool::is_queue_empty()
const
137 LockGuard lock(m_mutex);
138 return m_queue.empty();
141bool ThreadPool::wait_empty()
143 return is_queue_empty() || m_queueEmpty.wait();
146bool ThreadPool::wait_empty_for(
unsigned millisec)
148 return is_queue_empty() || m_queueEmpty.wait_for(millisec);
151void ThreadPool::suspend()
153 LockGuard lock(m_mutex);
157void ThreadPool::resume()
159 LockGuard lock(m_mutex);
164bool ThreadPool::is_suspended()
const
166 LockGuard lock(m_mutex);
170void ThreadPool::reset()
172 LockGuard lock(m_mutex);
175 while (!m_queue.empty())
177 delete m_queue.front();
182void ThreadPool::stop()
184 LockGuard lock(m_mutex);
188void ThreadPool::start()
190 LockGuard lock(m_mutex);
194bool ThreadPool::is_stopped()
const
196 LockGuard lock(m_mutex);
200Worker* ThreadPool::pop_queue(WorkerThread* _thread)
203 LockGuard lock(m_mutex);
206 m_queueEmpty.notify_one();
207 if (!m_queue.empty())
209 Worker* worker = m_queue.front();
217void ThreadPool::wait_queue(WorkerThread* _thread)
222 unsigned millisec = m_keepAlive;
224 m_queueFill.wait_for(millisec);
230void ThreadPool::start_thread(WorkerThread* _thread)
233 m_pool.insert(_thread);
234 if (!_thread->start_thread(
false))
235 finalize_thread(_thread);
238void ThreadPool::finalize_thread(WorkerThread* _thread)
240 LockGuard lock(m_mutex);
241 if (m_pool.erase(_thread))
249 m_condition.notify_all();
253void ThreadPool::__resize()
255 if (m_poolSize < m_size && !m_queue.empty())
257 for (
unsigned i = m_queue.size(); i > 0; --i)
259 if (m_poolSize >= m_size)
261 WorkerThread* _thread =
new WorkerThread(*
this);
263 start_thread(_thread);
266 else if (m_poolSize > m_size)
268 std::set<WorkerThread*>::iterator it = m_pool.begin();
269 for (
unsigned i = m_poolSize - m_size; i > 0; --i)
271 if (it == m_pool.end())
273 (*it)->stop_thread(
false);
278 m_queueFill.notify_all();