手写最简单线程池实现

线程池介绍

线程池是一种多线程处理形式,首先创建一些线程,它们的集合称为线程池,处理过程中将任务添加到队列,然后线程池就会启动一条线程来执行这个任务,执行结束以后,该线程并不会死亡,而是再次返回线程池中成为空闲状态,等待执行下一个任务。使用线程池目的是通过不断使用这些固定数量的线程调度进行处理,避免了在高并发情况下,不断开辟线程造成的进程资源消耗。下面是一个简单的线程池程序。

数据结构

主要有两个自定义的数据结构
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;
}

结果

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值