一、设计
线程池应该包括
- 保存线程的容器,保存任务的容器。
- 为了能保证避免线程对任务的竞态获取,需要对任务队列进行加锁。
- 为了使得工作线程感知任务的到来,需要使用条件变量来唤醒工作线程。
- 任务容器中的任务管理。
- 任务的处理API。
二、参数选择
使用数组存放线程,链表存放任务。
三、类设计
template<typename T>
class threadpool
{
public:
threadpool(int thread_num,int max_request);
~threadpool();
bool append(T* request);
private:
static void worker(void* arg);
void run();
private:
int m_thread_num;
int m_max_request;
pthread_t *m_threads;
std::list<T*>m_queuework;
sem m_sem;
lock m_locker;
};
template<typename T>
threadpool<T>::threadpool(int thread_num,int max_request):m_thread_num(thread_num),m_max_request(max_request)
{
if(thread_num <=0 || max_request <= 0) throw std::exception();
m_threads = new pthread_t[thread_num];
if(!m_threads) throw std::exception();
for(int i = 0;i < thread_num;++i)
{
if(pthread_create(m_threads + i, NULL,worker,this)!=0)
{
delete[] m_threads;
throw std::exception();
}
if(pthread_detach(m_threads[i]))
{
delete[] m_threads;
throw std::exception();
}
}
}
template<typename T>
threadpool<T>::~threadpool()
{
delete[] m_trheads;
}
template<typename T>
bool threadpool<T>::append(T* request)
{
m_locker.lock();
if(m_queuework.size() > m_max_request)
{
m_locker.unlock();
return false;
}
m_queuework.push_back(request);
m_locker.unlock();
m_sem.post();
return true;
}
template<typename T>
void* threadpool<T>::worker(void*arg)
{
threadpool* pool = (threadpool*)arg;
pool->run();
return pool;
}
template<typename T>
void threadpool<T>::run()
{
while(true)
{
m_sem.wait();
m_locker.lock();
if(m_queuework.empty())
{
m_locker.unlock();
continue;
}
T* request = m_queuework.front();
m_queuework.pop_front();
m_locker.unlock();
request.process();
}
}
|