Original Post
Im currently working on my threadpool for a library im making... I have a fairly nice base design, but it feels quite hackish. What I want to be able to do, is spawn new threads when the Task lists gains to size X (20 being X in this case). The design i have now works. Im able to sit in a continous while loop and push tasks into the pool and they will be correctly handled. But, once again, i feel the design in quite hackish. Any suggestions?
#ifndef H_THREADPOOL_H
#define H_THREADPOOL_H
#include "Thread.h"
#include <list>
#include "Mutex.h"
#include <boost/bind.hpp>
#include <boost/function.hpp>
class ThreadPool {
public:
/**
* Constructor
*/
ThreadPool() {
m_Mutex = new Mutex();
NewThread();
};
//==============================================================================
/**
* Destructor
*/
~ThreadPool() {
};
//==============================================================================
/**
* Adds an event to the pool.
*/
void QueueTask(boost::function<void()> _Callback) {
m_Mutex->AquireLock();
m_Tasks.push_back(_Callback);
if(m_Tasks.size() > 20 && m_Threads.size() < 300)
NewThread();
m_Mutex->ReleaseLock();
};
//===============================================================================
protected:
private:
list<boost::function<void()>> m_Tasks;
Mutex* m_Mutex;
list<IThread*> m_Threads;
//===============================================================================
/**
* Worker thread.
*/
void WorkerThread(IThread* _This) {
while(true) {
m_Mutex->AquireLock();
if(m_Tasks.size() > 0) {
m_Tasks.front()();
m_Tasks.pop_front();
}
printf("TaskCounter[%d] \n",m_Tasks.size());
m_Mutex->ReleaseLock();
wait(1);
}
};
//===============================================================================
/**
* Adds a new thread to the Pool.
*/
void NewThread() {
m_Mutex->AquireLock();
IThread* _Thread = 0;
_Thread = new Thread<ThreadPool,IThread*>(this, _Thread, &ThreadPool::WorkerThread);
_Thread->Execute();
m_Threads.push_back(_Thread);
m_Mutex->ReleaseLock();
};
//===============================================================================
};
#endif