2012-06-17 20:35:56 +02:00
|
|
|
#include "i2-base.h"
|
|
|
|
|
|
|
|
using namespace icinga;
|
|
|
|
|
|
|
|
ThreadPool::ThreadPool(long numThreads)
|
|
|
|
: m_Alive(true)
|
|
|
|
{
|
2012-06-19 09:38:20 +02:00
|
|
|
for (long i = 0; i < numThreads; i++)
|
|
|
|
m_Threads.create_thread(boost::bind(&ThreadPool::WorkerThreadProc, this));
|
2012-06-17 20:35:56 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
ThreadPool::~ThreadPool(void)
|
|
|
|
{
|
2012-06-18 06:44:26 +02:00
|
|
|
{
|
|
|
|
unique_lock<mutex> lock(m_Lock);
|
|
|
|
|
|
|
|
m_Tasks.clear();
|
2012-06-17 20:35:56 +02:00
|
|
|
|
2012-06-18 06:44:26 +02:00
|
|
|
/* notify worker threads to exit */
|
|
|
|
m_Alive = false;
|
|
|
|
m_CV.notify_all();
|
|
|
|
}
|
|
|
|
|
|
|
|
m_Threads.join_all();
|
2012-06-17 20:35:56 +02:00
|
|
|
}
|
|
|
|
|
2012-06-18 17:23:48 +02:00
|
|
|
void ThreadPool::EnqueueTasks(const vector<Task>& tasks)
|
|
|
|
{
|
|
|
|
unique_lock<mutex> lock(m_Lock);
|
|
|
|
|
|
|
|
std::copy(tasks.begin(), tasks.end(), std::back_inserter(m_Tasks));
|
|
|
|
m_CV.notify_all();
|
|
|
|
}
|
|
|
|
|
2012-06-17 20:35:56 +02:00
|
|
|
void ThreadPool::EnqueueTask(Task task)
|
|
|
|
{
|
|
|
|
unique_lock<mutex> lock(m_Lock);
|
2012-06-18 06:29:48 +02:00
|
|
|
m_Tasks.push_back(task);
|
2012-06-17 20:35:56 +02:00
|
|
|
m_CV.notify_one();
|
|
|
|
}
|
|
|
|
|
2012-06-18 06:44:26 +02:00
|
|
|
void ThreadPool::WaitForTasks(void)
|
|
|
|
{
|
|
|
|
unique_lock<mutex> lock(m_Lock);
|
|
|
|
|
|
|
|
/* wait for all pending tasks */
|
2012-06-19 09:38:20 +02:00
|
|
|
while (!m_Tasks.empty())
|
2012-06-18 06:44:26 +02:00
|
|
|
m_CV.wait(lock);
|
|
|
|
}
|
|
|
|
|
2012-06-17 20:35:56 +02:00
|
|
|
void ThreadPool::WorkerThreadProc(void)
|
|
|
|
{
|
|
|
|
while (true) {
|
|
|
|
Task task;
|
|
|
|
|
|
|
|
{
|
|
|
|
unique_lock<mutex> lock(m_Lock);
|
|
|
|
|
2012-06-19 09:38:20 +02:00
|
|
|
while (m_Tasks.empty()) {
|
2012-06-17 20:35:56 +02:00
|
|
|
if (!m_Alive)
|
|
|
|
return;
|
2012-06-18 06:44:26 +02:00
|
|
|
|
|
|
|
m_CV.wait(lock);
|
2012-06-17 20:35:56 +02:00
|
|
|
}
|
|
|
|
|
2012-06-18 06:29:48 +02:00
|
|
|
task = m_Tasks.front();
|
|
|
|
m_Tasks.pop_front();
|
2012-06-17 20:35:56 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
task();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
ThreadPool::Ptr ThreadPool::GetDefaultPool(void)
|
|
|
|
{
|
|
|
|
static ThreadPool::Ptr threadPool;
|
|
|
|
|
|
|
|
if (!threadPool)
|
|
|
|
threadPool = boost::make_shared<ThreadPool>();
|
|
|
|
|
|
|
|
return threadPool;
|
|
|
|
}
|