线程池_详解C语言实现的线程池

一、线程池功能定义:

  频繁的创建和启动线程会带来很大的开销,所以为了提高多线程任务处理效率,才有了线程池。其实池化技术都有一个特点,无论是内存池、线程池还是对象池等池化技术主要都是为了提高资源分配效率,预先分配一些资源在池子中,根据需要动态的调整和分配池中的资源(要弄清楚线程池,需要耐心阅读下面的代码哦,代码来自传智播客的教学资料)。
线程池工作基本原理

  上图是对线程池基本工作原理的描述,但是实际实现还需要管理者线程来对工作线程进行调配,管理者线程不参与工作。线程池需要具备以下基本功能:

1.需要维护一个任务队列,通过一个接口添加任务;

2.通过管理者线程定时去管理工作线程,工作线程通过竞争去抢任务;

3.定时根据目前情况动态的添加和杀死线程(通知他们自杀,具体实现请看代码);

4.管理线程池需要的相关内存空间;

5.维护互斥锁和条件变量实现线程的同步。

二、线程池的实现:

为了创建出一个具备基本功能的线程池,需要对线程池做如下定义:

typedef struct {
	 pthread_mutex_t lock;                 /* 用于控制线程池结构体成员变量访问的互斥锁 */
	 pthread_mutex_t thread_counter;       /* 用于控制忙线程数变量的互斥锁 */
	 pthread_cond_t  queue_not_full;       /* 条件变量,通知任务队列不为满 */
	 pthread_cond_t  queue_not_empty;      /* 条件变量,通知任务队列不为空 */
	
	 pthread_t *threads;                   /* 存放线程的tid,实际上就是管理了线程数组 */
	 pthread_t admin_tid;                  /* 管理者线程tid */
	 threadpool_task_t *task_queue;        /* 任务队列,其实是利用数组实现的环型队列*/
	
	 /*线程池信息*/
	 int min_thr_num;                      /* 线程池中最小线程数 */
	 int max_thr_num;                      /* 线程池中最大线程数 */
	 int live_thr_num;                     /* 线程池中存活的线程数 */
	 int busy_thr_num;                     /* 正在工作的线程数 */
	 int wait_exit_thr_num;                /* 等待销毁的线程数 */
	
	 /*任务队列信息*/
	 int queue_front;                      /* 队头 */
	 int queue_rear;                       /* 队尾 */
	 int queue_size;                       /* 任务队列当前大小 */
	 
	 /* 存在的任务数 */
	 int queue_max_size;                   /* 队列能容纳的最大任务数 */
	
	 /*状态*/
	 int shutdown;                         /* true为线程池关闭 */
} threadpool_t;

对任务做如下定义:

typedef struct {
    void* (*function)(void *); 	/*任务函数指针*/
	void* arg;					/*函数参数指针*/
} threadpool_task_t;

有了线程池的基本定义后,我们来看看这个线程池提供的接口:

/*创建线程池*/
threadpool_t *threadpool_create(int min_thr_num, int max_thr_num, int queue_max_size);

/*释放线程池*/
int threadpool_free(threadpool_t *pool);

/*销毁线程池*/
int threadpool_destroy(threadpool_t *pool);

/*管理线程*/
void *admin_thread(void *threadpool);

/*线程是否存在*/
int is_thread_alive(pthread_t tid);

/*工作线程*/
void *threadpool_thread(void *threadpool);

/*向线程池的任务队列中添加一个任务*/
int threadpool_add_task(threadpool_t *pool, void* (*function)(void *arg), void *arg);

看看是如何创建线程池的:

threadpool_t *
threadpool_create(int min_thr_num, int max_thr_num, int queue_max_size)
{
	   int i;
	   threadpool_t *pool = NULL;
	   do
	   {
	       if ((pool=(threadpool_t *)malloc(sizeof(threadpool_t))) == NULL)
		   {
	           printf("malloc threadpool fail; \n");
			   break;   
		   }
		    /*信息初始化*/
		   pool->min_thr_num = min_thr_num;
		   pool->max_thr_num = max_thr_num;
		   pool->busy_thr_num = 0;
		   pool->live_thr_num = min_thr_num;
		   pool->wait_exit_thr_num = 0;
		   pool->queue_front = 0;
		   pool->queue_rear = 0;
		   pool->queue_size = 0;
		   pool->queue_max_size = queue_max_size;
		   pool->shutdown = false;
		   
		   /*根据最大线程数,给工作线程数组开空间,清0*/
		   pool->threads = (pthread_t *)malloc(sizeof(pthread_t)*max_thr_num);
		   if (pool->threads == NULL)
		   {
		        printf("malloc threads fail;\n");
				break; //如果分配失败跳出do while语句,释放pool申请的空间并返回NULL
		   }
		   //空间初始化为0,分配空间的时候考虑用calloc是不是会更好?
		   memset(pool->threads, 0, sizeof(pthread_t)*max_thr_num);
		
		   /*队列开空间*/
		   pool->task_queue = \
		   (threadpool_task_t *)malloc(sizeof(threadpool_task_t)*queue_max_size);
		   if (pool->task_queue == NULL)
		   {
		        printf("malloc task queue fail;\n");
			    break;
		   }
		
		   /*初始化互斥锁和条件变量*/
		   if ( pthread_mutex_init(&(pool->lock), NULL) != 0           ||   \
		        pthread_mutex_init(&(pool->thread_counter), NULL) !=0  ||   \
			    pthread_cond_init(&(pool->queue_not_empty), NULL) !=0  ||   \
			    pthread_cond_init(&(pool->queue_not_full), NULL) !=0 )
		   {
		        printf("init lock or cond fail;\n");
		        break;
		   }
		
		      /*启动min_thr_num个工作线程*/
		   for (i = 0; i < min_thr_num; i++)
		   {
		        /*pool指向当前线程池*/
		        pthread_create(&(pool->threads[i]), NULL, threadpool_thread, (void *)pool);
			 	printf("start thread 0x%x... \n", (unsigned int)pool->threads[i]);
		   }
		   /*管理者线程*/
		   pthread_create(&(pool->admin_tid), NULL, admin_thread, (void *)pool);
		   return pool;
   } while(0);

   /*如果跳出do while则释放pool的空间*/
   threadpool_free(pool);
   return NULL;
}

线程池空间是如何释放的:

int 
threadpool_free(threadpool_t *pool)
{
	   //先判断是否为空,为空直接退出,避免2次free
	   if (pool == NULL)
	   {
	        return -1;
	   }
	
	   if (pool->task_queue)
	   {
	       free(pool->task_queue);
	   }
	   if (pool->threads)
	   {
		   free(pool->threads);
		   pthread_mutex_lock(&(pool->lock));               /*先锁住再销毁*/
		   pthread_mutex_destroy(&(pool->lock));
		   pthread_mutex_lock(&(pool->thread_counter));
           pthread_mutex_destroy(&(pool->thread_counter));
 	       pthread_cond_destroy(&(pool->queue_not_empty));
		   pthread_cond_destroy(&(pool->queue_not_full));
	   }
	   free(pool);
	   pool = NULL;
	
	   return 0;
}

线程池是如何销毁的:

int 
threadpool_destroy(threadpool_t *pool)
{
	   int i;
	   if (pool == NULL)
	   {
	     	return -1;
	   }
	   pool->shutdown = true;
	
	   /*销毁管理者线程*/
	   pthread_join(pool->admin_tid, NULL);
	
	   //通知所有线程去自杀(在自己领任务的过程中)
	   for (i = 0; i < pool->live_thr_num; i++)
	   { 
	     	//广播通知给持有该信号量的线程
	     	pthread_cond_broadcast(&(pool->queue_not_empty));
	   }
	
	   /*等待线程结束 先是pthread_exit 然后等待其结束*/
	   for (i = 0; i < pool->live_thr_num; i++)
	   {
		     pthread_join(pool->threads[i], NULL);//回收线程资源
	   }
	
	   threadpool_free(pool);
	   return 0;
}

管理线程是如何创建的:

void *
admin_thread(void *threadpool)
{
	   int i;
	   threadpool_t *pool = (threadpool_t *)threadpool;
	   while (!pool->shutdown)
	   {
		      printf("admin -----------------\n");
		      sleep(DEFAULT_TIME);                             /*隔一段时间再管理*/
		      pthread_mutex_lock(&(pool->lock));               /*加锁*/ 
		      int queue_size = pool->queue_size;               /*任务数*/
		      int live_thr_num = pool->live_thr_num;           /*存活的线程数*/
		      pthread_mutex_unlock(&(pool->lock));             /*解锁*/
		      
		      pthread_mutex_lock(&(pool->thread_counter));
		      int busy_thr_num = pool->busy_thr_num;           /*忙线程数*/  
		      pthread_mutex_unlock(&(pool->thread_counter));
		
		      printf("admin busy live -%d-/-%d-\n", busy_thr_num, live_thr_num);
		      /*当实际任务数量超过允许等待的最小任务数量且存活线程数小于等于最大线程数,创建新线程*/
		      if (queue_size >= MIN_WAIT_TASK_NUM && live_thr_num <= pool->max_thr_num)
		      {
			         printf("admin add-----------\n");
			         pthread_mutex_lock(&(pool->lock));
			         int add=0;
			
			         /*一次增加 DEFAULT_THREAD_NUM 个线程*/
			         //遍历线程数组,找到合适的位置
					 for (i = 0; i < pool->max_thr_num && add < DEFAULT_THREAD_NUM  \
					     && pool->live_thr_num < pool->max_thr_num; i++)
					 {	
					     //当前线程数组中的线程没有使用过或者已经死掉了就可以在当前位置创建新线程
					     if (pool->threads[i] == 0 || !is_thread_alive(pool->threads[i]))
					     {
						     pthread_create(&(pool->threads[i]), NULL, threadpool_thread, (void *)pool);
						     add++;
						     pool->live_thr_num++;
						     printf("new thread -----------------------\n");
					     }
				     }
				     pthread_mutex_unlock(&(pool->lock));
             }  

	      /*销毁多余的线程 忙线程x2 都小于 存活线程,并且存活的大于最小线程数*/
	      if ((busy_thr_num*2) < live_thr_num  &&  live_thr_num > pool->min_thr_num)
	      {
		         // printf("admin busy --%d--%d----\n", busy_thr_num, live_thr_num);
		         /*一次销毁DEFAULT_THREAD_NUM个线程*/
			 	 pthread_mutex_lock(&(pool->lock));
		         pool->wait_exit_thr_num = DEFAULT_THREAD_NUM;
			 	 pthread_mutex_unlock(&(pool->lock));
		
				 for (i = 0; i < DEFAULT_THREAD_NUM; i++)
				 {
				     //通知一个正在处于空闲的线程,自杀
				     pthread_cond_signal(&(pool->queue_not_empty));
				     printf("admin cler --\n");
				 }
	      }
   }
   return NULL;
}

/*判断线程是否存活*/
int 
is_thread_alive(pthread_t tid)
{
    int kill_rc = pthread_kill(tid, 0);     //发送0号信号,测试是否存活
	if (kill_rc == ESRCH)  //线程不存在
	{
	   return false;
	}
	return true;
}

看看工作线程是如何工作的(重点):

void *
threadpool_thread(void *threadpool)
{
	  threadpool_t *pool = (threadpool_t *)threadpool;
	  threadpool_task_t task;
	
	  while (true)
	  {
	      pthread_mutex_lock(&(pool->lock));
		
		  //无任务则阻塞在条件变量queue_not_empty的wait上,有任务则跳出
		  while ((pool->queue_size == 0) && (!pool->shutdown))
		  { 
		      printf("thread 0x%x is waiting \n", (unsigned int)pthread_self());
		      pthread_cond_wait(&(pool->queue_not_empty), &(pool->lock));
		
		     //判断是否需要清除线程,自杀功能
		     if (pool->wait_exit_thr_num > 0)
		     {
		         pool->wait_exit_thr_num--;
		         //判断线程池中的线程数是否大于最小线程数,是则结束当前线程
				 if (pool->live_thr_num > pool->min_thr_num)
				 {
				     printf("thread 0x%x is exiting \n", (unsigned int)pthread_self());
				     pool->live_thr_num--;
				     pthread_mutex_unlock(&(pool->lock));
				     pthread_exit(NULL);//结束线程
				 }
		     }
		  }
		
		  //线程池开关状态
		  if (pool->shutdown) //关闭线程池
		  {
		      pthread_mutex_unlock(&(pool->lock));
		      printf("thread 0x%x is exiting \n", (unsigned int)pthread_self());
		      pthread_exit(NULL); //线程自己结束自己
		  }
		
		  //否则该线程可以拿出任务
		  task.function = pool->task_queue[pool->queue_front].function; //出队操作
		  task.arg = pool->task_queue[pool->queue_front].arg;
		
		  pool->queue_front = (pool->queue_front + 1) % pool->queue_max_size;  //利用数组实现的环型队列
		  pool->queue_size--;
		
		  //通知可以添加新任务
		  pthread_cond_broadcast(&(pool->queue_not_full));
		    
		  //释放线程锁
		  pthread_mutex_unlock(&(pool->lock));
		    
		  //执行刚才取出的任务
		  printf("thread 0x%x start working \n", (unsigned int)pthread_self());
		  pthread_mutex_lock(&(pool->thread_counter));            //锁住忙线程变量
		  pool->busy_thr_num++;
		  pthread_mutex_unlock(&(pool->thread_counter));
		
		  (*(task.function))(task.arg);                           //执行任务
		
		  //任务结束处理
		  printf("thread 0x%x end working \n", (unsigned int)pthread_self());
		  pthread_mutex_lock(&(pool->thread_counter));
		  pool->busy_thr_num--;
	      pthread_mutex_unlock(&(pool->thread_counter));
    }
	pthread_exit(NULL);
}

如何向线程池中添加任务:

int 
threadpool_add_task(threadpool_t *pool, void *(*function)(void *arg), void *arg)
{
    pthread_mutex_lock(&(pool->lock));

    /*如果队列满了,调用wait阻塞*/
    while ((pool->queue_size == pool->queue_max_size) && (!pool->shutdown))
    {
        pthread_cond_wait(&(pool->queue_not_full), &(pool->lock));
    }
    /*如果线程池处于关闭状态*/
    if (pool->shutdown)
    {
        pthread_mutex_unlock(&(pool->lock));
        return -1;
    }

    /*清空工作线程的回调函数的参数arg*/
    if (pool->task_queue[pool->queue_rear].arg != NULL)
    {
        free(pool->task_queue[pool->queue_rear].arg);
        pool->task_queue[pool->queue_rear].arg = NULL;
    }
   
    /*添加任务到任务队列*/
    pool->task_queue[pool->queue_rear].function = function;
    pool->task_queue[pool->queue_rear].arg = arg;
    pool->queue_rear = (pool->queue_rear + 1) % pool->queue_max_size;  /* 逻辑环  */
    pool->queue_size++;

    /*添加完任务后,队列就不为空了,唤醒线程池中的一个线程*/
    pthread_cond_signal(&(pool->queue_not_empty));
    pthread_mutex_unlock(&(pool->lock));
    
    return 0;
}

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值