2 #include "CThreadPool.h"
5 void CTask::SetData(void * data
)
10 void CTask::releaseData()
12 if (m_ptrData
!= NULL
)
16 TaskList
CThreadPool::m_TaskList
; //任务列表
17 bool CThreadPool::shutdown
= false;
19 pthread_mutex_t
CThreadPool::m_pthreadMutex
= PTHREAD_MUTEX_INITIALIZER
;
20 pthread_cond_t
CThreadPool::m_pthreadCond
= PTHREAD_COND_INITIALIZER
;
21 int CThreadPool::m_task_count
= 0;
26 CThreadPool::CThreadPool(int threadNum
)
28 this->m_iThreadNum
= threadNum
;
35 void* CThreadPool::ThreadFunc(void* threadData
)
37 pthread_t tid
= pthread_self();
40 pthread_mutex_lock(&m_pthreadMutex
);
41 while (m_TaskList
.size() == 0 && !shutdown
)
43 pthread_cond_wait(&m_pthreadCond
, &m_pthreadMutex
);
48 pthread_mutex_unlock(&m_pthreadMutex
);
52 TaskList::iterator iter
= m_TaskList
.begin();
58 if (iter
!= m_TaskList
.end())
61 m_TaskList
.pop_front();
64 pthread_mutex_unlock(&m_pthreadMutex
);
66 task
->Run(); /** 执行任务 */
67 pthread_mutex_lock(&m_pthreadMutex
);
69 pthread_mutex_unlock(&m_pthreadMutex
);
75 * 往任务队列里边添加任务并发出线程同步信号
77 int CThreadPool::AddTask(CTask
*task
)
79 pthread_mutex_lock(&m_pthreadMutex
);
80 this->m_TaskList
.push_back(task
);
82 pthread_mutex_unlock(&m_pthreadMutex
);
83 pthread_cond_signal(&m_pthreadCond
);
91 int CThreadPool::Create()
93 pthread_id
= (pthread_t
*)malloc(sizeof(pthread_t
) * m_iThreadNum
);
94 for(int i
= 0; i
< m_iThreadNum
; i
++)
96 pthread_create(&pthread_id
[i
], NULL
, ThreadFunc
, NULL
);
104 int CThreadPool::StopAll()
111 /** 唤醒所有等待线程,线程池要销毁了 */
113 pthread_cond_broadcast(&m_pthreadCond
);
115 /** 阻塞等待线程退出,否则就成僵尸了 */
116 for (int i
= 0; i
< m_iThreadNum
; i
++)
118 pthread_join(pthread_id
[i
], NULL
);
125 pthread_mutex_destroy(&m_pthreadMutex
);
126 pthread_cond_destroy(&m_pthreadCond
);
134 int CThreadPool::getTaskSize()