22 #include "threadpool.h" 26 #define WTH_KEEPALIVE 5000 34 CThreadPool::CThreadPool()
36 , m_keepAlive(WTH_KEEPALIVE)
45 CThreadPool::CThreadPool(
unsigned size)
47 , m_keepAlive(WTH_KEEPALIVE)
56 CThreadPool::~CThreadPool()
62 while (!m_queue.empty())
64 delete m_queue.front();
72 for (std::set<CWorkerThread*>::iterator it = m_pool.begin(); it != m_pool.end(); ++it)
73 (*it)->StopThread(
false);
75 m_queueFill.Broadcast();
77 m_condition.Wait(m_mutex, m_empty);
81 bool CThreadPool::Enqueue(
CWorker* worker)
83 assert(worker->m_queued !=
true);
87 worker->m_queued =
true;
109 void CThreadPool::SetMaxSize(
unsigned size)
117 void CThreadPool::SetKeepAlive(
unsigned millisec)
120 m_keepAlive = millisec;
123 unsigned CThreadPool::Size()
const 129 unsigned CThreadPool::QueueSize()
const 132 return static_cast<unsigned>(m_queue.size());
135 bool CThreadPool::IsQueueEmpty()
const 138 return m_queue.empty();
141 bool CThreadPool::waitEmpty(
unsigned millisec)
143 return IsQueueEmpty() || m_queueEmpty.Wait(millisec);
146 bool CThreadPool::waitEmpty()
148 return IsQueueEmpty() || m_queueEmpty.Wait();
151 void CThreadPool::Suspend()
157 void CThreadPool::Resume()
164 bool CThreadPool::IsSuspended()
const 170 void CThreadPool::Reset()
175 while (!m_queue.empty())
177 delete m_queue.front();
182 void CThreadPool::Stop()
188 void CThreadPool::Start()
194 bool CThreadPool::IsStopped()
const 206 m_queueEmpty.Signal();
207 if (!m_queue.empty())
209 CWorker* worker = m_queue.front();
222 unsigned millisec = m_keepAlive;
224 m_queueFill.Wait(millisec);
232 m_pool.insert(_thread);
233 if (!_thread->StartThread(
false))
234 FinalizeThread(_thread);
240 if (m_pool.erase(_thread))
248 m_condition.Broadcast();
252 void CThreadPool::__resize()
254 if (m_poolSize < m_size && !m_queue.empty())
256 for (
unsigned i = m_queue.size(); i > 0; --i)
258 if (m_poolSize >= m_size)
262 StartThread(_thread);
265 else if (m_poolSize > m_size)
267 std::set<CWorkerThread*>::iterator it = m_pool.begin();
268 for (
unsigned i = m_poolSize - m_size; i > 0; --i)
270 if (it == m_pool.end())
272 (*it)->StopThread(
false);
277 m_queueFill.Broadcast();