资源简介
linux下封装的线程池类 和 任务基类
根据具体业务继承任务基类
线程池内使用条件变量来调度任务
代码片段和文件信息
#include “threadpool.h“
CTask::~CTask()
{
}
CTask::CTask()
{
m_nDoFlag=1;
}
CThreadPool::CThreadPool( int nThreadCount )
{
m_nThreadCount=nThreadCount;
}
CThreadPool::~CThreadPool()
{
Fini();
}
void CThreadPool::AddThread(int nCount)
{
}
int CThreadPool::Init()
{
pthread_mutex_init(&m_taskMutexNULL);
pthread_mutex_init(&m_taskListMutexNULL);
pthread_mutex_init(&m_threadListMutexNULL);
pthread_cond_init(&m_taskCondNULL);
// init thread
for (int i=0;i {
CThreadItem* pItem=new CThreadItem(ithis);
m_threadList.push_back(pItem);
}
return 0;
}
void CThreadPool::Fini()
{
list::iterator itor;
for (itor=m_threadList.begin();itor!=m_threadList.end();itor++)
{
CThreadItem* pItem=*itor;
if (pItem)
{
pItem->SetQuit();
}
}
pthread_cond_broadcast(&m_taskCond);
for (itor=m_threadList.begin();itor!=m_threadList.end();itor++)
{
CThreadItem* pItem=*itor;
if (pItem)
{
delete pItem;
}
}
pthread_mutex_destroy(&m_taskMutex);
pthread_mutex_destroy(&m_taskListMutex);
pthread_mutex_destroy(&m_threadListMutex);
}
void CThreadPool::AddTask( CTask* pTask )
{
if (!pTask)
{
return;
}
pthread_mutex_lock(&m_taskListMutex);
m_taskList.push_back(pTask);
pthread_mutex_unlock(&m_taskListMutex);
pthread_cond_signal(&m_taskCond);
}
CThreadItem::CThreadItem(int nIDCThreadPool* pThreadPool )
{
m_nID=nID;
m_hThreadHandle=0;
m_nThreadFlag=1;
m_pThreadPool=pThreadPool;
// create thread
int nError=pthread_create(&m_hThreadHandleNULLTreatTaskThreadthis);
if (0!=nError)
{
printf(“create thread failed nid:%d \n“m_nID);
}
else
{
printf(“create thread nid:%d threadhandle:%lu \n“m_nIDm_hThreadHandle);
}
}
CThreadItem::~CThreadItem()
{
if (m_hThreadHandle)
{
m_nThreadFlag=0;
pthread_join(m_hThreadHandleNULL);
printf(“leave the thread nID: %d threadhandle %lu \n“m_nIDm_hThreadHandle);
m_hThreadHandle=0;
}
}
void CThreadItem::OnTreatTaskThread()
{
while (m_nThreadFlag)
{
pthread_mutex_lock(&m_pThreadPool->m_taskMutex);
pthread_cond_wait(&m_pThreadPool->m_taskCond &m_pThreadPool->m_taskMutex);
pthread_mutex_unlock(&m_pThreadPool->m_taskMutex);
// get task and do it
pthread_mutex_lock(&m_pThreadPool->m_taskListMutex);
if (m_pThreadPool->m_taskList.size()>0)
{
CTask* pTask=m_pThreadPool->m_taskList.front();
m_pThreadPool->m_taskList.pop_front();
pthread_mutex_unlock(&m_pThreadPool->m_taskListMutex);
if (pTask)
{
int nRet=pTask->Do();
printf(“task being treated by thread handle :%lu \n“m_hThreadHandle);
if (0==nRet)
{
delete pTask;
}
}
}
else
{
pthread_mutex_unlock(&m_pThreadPool->m_taskListMutex);
}
}
}
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 2878 2014-06-11 20:41 thread\threadpool.cpp
文件 1494 2014-06-11 20:41 thread\threadpool.h
目录 0 2014-07-14 13:49 thread
----------- --------- ---------- ----- ----
4372 3
评论
共有 条评论