//SRThreadPool.h
#pragma once
#include "SRTask.h"
#include <boost/thread.hpp>
#include <deque>
class ThreadPool;
class ThreadFunc
{
public:
ThreadFunc(ThreadPool& pool): threadpool(pool) {}
void operator()();
private:
ThreadFunc();
ThreadPool& threadpool;
};
class ThreadPool
{
friend class ThreadFunc;
public:
ThreadPool(size_t nbOfThreads);
void SubmitTask(SRTask& task);
private:
ThreadPool();
bool stop;
size_t numThreads;
boost::mutex queueMutex;
std::deque<SRTask> taskQueue;
std::vector<boost::thread> threads;
};
// SRThreadPool.cpp
#include "Precompiled.h"
#include "SRThreadPool.h"
void ThreadFunc::operator()()
{
while(true)
{
if(threadpool.stop)
break;
// Might want to use boost::optional here
threadpool.queueMutex.lock();
if(threadpool.taskQueue.size() > 0)
{
SRTask t = threadpool.taskQueue.front();
threadpool.taskQueue.pop_front();
threadpool.queueMutex.unlock();
t();
}
else
{
threadpool.queueMutex.unlock();
}
}
}
ThreadPool::ThreadPool(size_t nbOfThreads): numThreads(nbOfThreads), stop(false), threads(0)
{
for(size_t i=0; i<numThreads; i++)
{
threads.emplace_back(boost::thread(ThreadFunc(*this)));
}
}
void ThreadPool::SubmitTask(SRTask& task)
{
queueMutex.lock();
taskQueue.push_back(task);
queueMutex.unlock();
}