线程池介绍
线程池是一种多线程处理形式,首先创建一些线程,它们的集合称为线程池,处理过程中将任务添加到队列,然后线程池就会启动一条线程来执行这个任务,执行结束以后,该线程并不会死亡,而是再次返回线程池中成为空闲状态,等待执行下一个任务。使用线程池目的是通过不断使用这些固定数量的线程调度进行处理,避免了在高并发情况下,不断开辟线程造成的进程资源消耗。下面是一个简单的线程池程序。
数据结构
主要有两个自定义的数据结构
Task
用于保存一个等待执行的任务。
class Task{
public:
virtual void Run() = 0; //函数指针,需要执行的任务
virtual ~Task() {};
};
ThreadPool
一个线程池的结构。
class ThreadPool{
public:
//初始化线程池
bool ThreadpoolCreate(int pthread_num);
// 添加任务到线程池
void AddTaskToPoll(Task *task);
private:
static void *RunTask(void *argv);
void Working();
private:
pthread_mutex_t thread_lock;
pthread_cond_t thread_cond;
std::list<Task*> task_list; //任务队列
};
函数实现
bool ThreadPool::ThreadpoolCreate(int pthread_num){
assert(pthread_num > 0);
//初始化锁条件变量
pthread_mutex_init(&thread_lock, NULL);
pthread_cond_init(&thread_cond, NULL);
pthread_t pth_t;
for (int i = 0; i < pthread_num; ++i){
pthread_create(&pth_t, NULL, ThreadPool::RunTask, this);
}
return true;
}
void *ThreadPool::RunTask(void *argv){
ThreadPool *pool_t = static_cast<ThreadPool *>(argv);
pool_t->Working();
return NULL;
}
void ThreadPool::Working(){
//线程循环处理
for( ; ; ){
pthread_mutex_lock(&thread_lock);
while (0 == task_list.size()){
pthread_cond_wait(&thread_cond, &thread_lock);
}
Task *task = task_list.front();
task_list.pop_front();
pthread_mutex_unlock(&thread_lock);
task->Run();
delete task;
}
}
void ThreadPool::AddTaskToPoll(Task *task){
if (NULL == task){
return;
}
pthread_mutex_lock(&thread_lock);
task_list.push_back(task);
pthread_mutex_unlock(&thread_lock);
pthread_cond_signal(&thread_cond);
}
测试用例
class MyTask: public Task{
public:
void Run(){
printf("%s\n", data.c_str());
}
void SetData(const std::string &task_data){
data = task_data;
}
private:
std::string data;
};
int main(int argc, char **argv)
{
ThreadPool thread_pool;
thread_pool.ThreadpoolCreate(4);
char str[32];
for(int i = 0; i < 10; ++i){
MyTask *task = new MyTask();
memset(str, 0, 32);
sprintf(str, "Task number %d", i);
task->SetData(str);
thread_pool.AddTaskToPoll(task);
}
return 0;
}