线程池

来源:互联网 发布:长沙蓝狐网络官网 编辑:程序博客网 时间:2024/06/05 09:21

线程池基本原理

在传统服务器结构中,常是有一个总的监听线程监听有没有新的用户连接服务器,每当有一个新的用户进入,服务器就开启一个新的线程用户处理这 个用户的数据包。这个线程只服务于这个用户,当用户与服务器端关闭连接以后,服务器端销毁这个线程。(关于并发服务器更多详情,请看《并发服务器》)。


然而频繁地开辟与销毁线程极大地占用了系统的资源,而且在大量用户的情况下,系统为了开辟和销毁线程将浪费大量的时间和资源。线程池提供了一个解决外部大量用户与服务器有限资源的矛盾。


线程池和传统的一个用户对应一个线程的处理方法不同,它的基本思想就是在程序开始时就在内存中开辟一些线程,线程的数目是固定的,他们独自形成一个类,屏蔽了对外的操作,而服务器只需要将数据包交给线程池就可以了。当有新的客户请求到达时,不是新创建一个线程为其服务,而是从“池子”中选择一个空闲的线程为新的客户请求服务,服务完毕后,线程进入空闲线程池中。如果没有线程空闲的话,就将数据包暂时积累, 等待线程池内有线程空闲以后再进行处理。通过对多个任务重用已经存在的线程对象,降低了对线程对象创建和销毁的开销。当客户请求 时,线程对象已经存在,可以提高请求的响应时间,从而整体地提高了系统服务的表现。


线程池应用实例

一般来说实现一个线程池主要包括以下几个组成部分:

1)线程管理器:用于创建并管理线程池。


2)工作线程:线程池中实际执行任务的线程。在初始化线程时会预先创建好固定数目的线程在池中,这些初始化的线程一般处于空闲状态,一般不占用 CPU,占用较小的内存空间。


3)任务接口:每个任务必须实现的接口,当线程池的任务队列中有可执行任务时,被空闲的工作线程调去执行(线程的闲与忙是通过互斥量实现的),把任务抽象出来形成接口,可以做到线程池与具体的任务无关。


4)任务队列:用来存放没有处理的任务,提供一种缓冲机制,实现这种结构有好几种方法,常用的是队列,主要运用先进先出原理,另外一种是链表之类的数据结构,可以动态的为它分配内存空间,应用中比较灵活,此教程就是用到的链表。


什么时候需要创建线程池呢?简单的说,如果一个应用需要频繁的创建和销毁线程,而任务执行的时间又非常短,这样线程创建和销毁的带来的开销就不容忽视,这时也是线程池该出场的机会了。如果线程创建和销毁时间相比任务执行时间可以忽略不计,则没有必要使用线程池了。


线程池实现示例代码如下:


thread_pool.h 的示例代码:

[cpp] view plaincopy
  1. #ifndef __THREAD_POOL_H__  
  2. #define __THREAD_POOL_H__  
  3.   
  4. #include <pthread.h>  
  5.   
  6.  /********************************************************************* 
  7. * 任务回调函数,也可根据需要自行修改 
  8. *********************************************************************/  
  9. typedef void *(*pool_task_f)(void *arg);  
  10.   
  11. /********************************************************************* 
  12. * 任务句柄 
  13. *********************************************************************/  
  14. typedef struct _task{  
  15.     pool_task_f process;/*回调函数,任务运行时会调用此函数,注意也可声明成其它形式*/  
  16.     void *arg;     /*回调函数的参数*/  
  17.     struct _task *next;  
  18. }pool_task;  
  19.   
  20. /********************************************************************* 
  21. * 线程池句柄 
  22. *********************************************************************/  
  23. typedef struct  
  24. {  
  25.     pthread_t *threadid;        /* 线程号 */  
  26.     int threads_limit;          /* 线程池中允许的活动线程数目 */  
  27.     int destroy_flag;           /* 是否销毁线程池 , 0销毁,1不销毁*/  
  28.     pool_task *queue_head;      /* 链表结构,线程池中所有等待任务 */  
  29.     int task_in_queue;          /* 当前等待队列的任务数目 */  
  30.     pthread_mutex_t queue_lock; /* 锁 */  
  31.     pthread_cond_t queue_ready; /* 条件变量 */  
  32. }pool_t;  
  33.   
  34. /********************************************************************* 
  35. *功能:        初始化线程池结构体并创建线程 
  36. *参数:         
  37.             pool:线程池句柄 
  38.             threads_limit:线程池中线程的数量 
  39. *返回值:   无 
  40. *********************************************************************/  
  41. void pool_init(pool_t *pool, int threads_limit);  
  42.   
  43. /********************************************************************* 
  44. *功能:        销毁线程池,等待队列中的任务不会再被执行, 
  45.             但是正在运行的线程会一直,把任务运行完后再退出 
  46. *参数:        线程池句柄 
  47. *返回值:   成功:0,失败非0 
  48. *********************************************************************/  
  49. int pool_uninit(pool_t *pool);  
  50.   
  51. /********************************************************************* 
  52. *功能:        向线程池中添加一个任务 
  53. *参数:         
  54.             pool:线程池句柄 
  55.             process:任务处理函数 
  56.             arg:任务参数 
  57. *返回值:   0 
  58. *********************************************************************/  
  59. int pool_add_task(pool_t *pool, pool_task_f process, void *arg);  
  60.   
  61.   
  62. #endif  


thread_pool.c 的示例代码:
[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <pthread.h>  
  4. #include <assert.h>  
  5.   
  6. #include "thread_pool.h"  
  7.   
  8. static void *pool_thread_server(void *arg);  
  9.   
  10. /********************************************************************* 
  11. *功能:        初始化线程池结构体并创建线程 
  12. *参数:         
  13.             pool:线程池句柄 
  14.             threads_limit:线程池中线程的数量 
  15. *返回值:   无 
  16. *********************************************************************/  
  17. void pool_init(pool_t *pool, int threads_limit)  
  18. {  
  19.     pool->threads_limit = threads_limit;  
  20.     pool->queue_head = NULL;  
  21.     pool->task_in_queue = 0;  
  22.     pool->destroy_flag = 0;  
  23.     /*创建存放线程ID的空间*/  
  24.     pool->threadid = (pthread_t *)calloc(threads_limit, sizeof(pthread_t));  
  25.     int i = 0;  
  26.     /*初始化互斥锁和条件变量*/  
  27.     pthread_mutex_init(&(pool->queue_lock), NULL);  
  28.     pthread_cond_init(&(pool->queue_ready), NULL);  
  29.     /*循环创建threads_limit个线程*/  
  30.     for (i = 0; i < threads_limit; i++){  
  31.         pthread_create(&(pool->threadid[i]), NULL, pool_thread_server, pool);  
  32.     }  
  33.     return;  
  34. }  
  35.   
  36. /********************************************************************* 
  37. *功能:        销毁线程池,等待队列中的任务不会再被执行, 
  38.             但是正在运行的线程会一直,把任务运行完后再退出 
  39. *参数:        线程池句柄 
  40. *返回值:   成功:0,失败非0 
  41. *********************************************************************/  
  42. int pool_uninit(pool_t *pool)  
  43. {  
  44.     pool_task *head = NULL;  
  45.     int i;  
  46.       
  47.     pthread_mutex_lock(&(pool->queue_lock));  
  48.     if(pool->destroy_flag)/* 防止两次调用 */  
  49.         return -1;  
  50.     pool->destroy_flag = 1;  
  51.     pthread_mutex_unlock(&(pool->queue_lock));  
  52.     /* 唤醒所有等待线程,线程池要销毁了 */  
  53.     pthread_cond_broadcast(&(pool->queue_ready));  
  54.     /* 阻塞等待线程退出,否则就成僵尸了 */  
  55.     for (i = 0; i < pool->threads_limit; i++)  
  56.         pthread_join(pool->threadid[i], NULL);  
  57.     free(pool->threadid);  
  58.     /* 销毁等待队列 */  
  59.     pthread_mutex_lock(&(pool->queue_lock));  
  60.     while(pool->queue_head != NULL){  
  61.         head = pool->queue_head;  
  62.         pool->queue_head = pool->queue_head->next;  
  63.         free(head);  
  64.     }  
  65.     pthread_mutex_unlock(&(pool->queue_lock));  
  66.     /*条件变量和互斥量也别忘了销毁*/  
  67.     pthread_mutex_destroy(&(pool->queue_lock));  
  68.     pthread_cond_destroy(&(pool->queue_ready));  
  69.     return 0;  
  70. }  
  71.   
  72. /********************************************************************* 
  73. *功能:        向任务队列中添加一个任务 
  74. *参数:         
  75.             pool:线程池句柄 
  76.             process:任务处理函数 
  77.             arg:任务参数 
  78. *返回值:   无 
  79. *********************************************************************/  
  80. static void enqueue_task(pool_t *pool, pool_task_f process, void *arg)  
  81. {  
  82.     pool_task *task = NULL;  
  83.     pool_task *member = NULL;  
  84.       
  85.     pthread_mutex_lock(&(pool->queue_lock));  
  86.       
  87.     if(pool->task_in_queue >= pool->threads_limit){  
  88.         printf("task_in_queue > threads_limit!\n");  
  89.         pthread_mutex_unlock (&(pool->queue_lock));  
  90.         return;  
  91.     }  
  92.       
  93.     task = (pool_task *)calloc(1, sizeof(pool_task));  
  94.     assert(task != NULL);  
  95.     task->process = process;  
  96.     task->arg = arg;  
  97.     task->next = NULL;  
  98.     pool->task_in_queue++;  
  99.     member = pool->queue_head;  
  100.     if(member != NULL){  
  101.         while(member->next != NULL)  /* 将任务加入到任务链连的最后位置. */  
  102.             member = member->next;  
  103.         member->next = task;  
  104.     }else{  
  105.         pool->queue_head = task; /* 如果是第一个任务的话,就指向头 */  
  106.     }  
  107.     printf("\ttasks %d\n", pool->task_in_queue);  
  108.     /* 等待队列中有任务了,唤醒一个等待线程 */  
  109.     pthread_cond_signal (&(pool->queue_ready));  
  110.     pthread_mutex_unlock (&(pool->queue_lock));  
  111. }  
  112.   
  113. /********************************************************************* 
  114. *功能:        从任务队列中取出一个任务 
  115. *参数:        线程池句柄 
  116. *返回值:   任务句柄 
  117. *********************************************************************/  
  118. static pool_task *dequeue_task(pool_t *pool)  
  119. {  
  120.     pool_task *task = NULL;  
  121.       
  122.     pthread_mutex_lock(&(pool->queue_lock));  
  123.     /* 判断线程池是否要销毁了 */  
  124.     if(pool->destroy_flag){  
  125.         pthread_mutex_unlock(&(pool->queue_lock));  
  126.         printf("thread 0x%lx will be destroyed\n", pthread_self());  
  127.         pthread_exit(NULL);  
  128.     }  
  129.     /* 如果等待队列为0并且不销毁线程池,则处于阻塞状态 */  
  130.     if(pool->task_in_queue == 0){  
  131.         while((pool->task_in_queue == 0) && (!pool->destroy_flag)){  
  132.             printf("thread 0x%lx is waitting\n", pthread_self());  
  133.             /* 注意:pthread_cond_wait是一个原子操作,等待前会解锁,唤醒后会加锁 */  
  134.             pthread_cond_wait(&(pool->queue_ready), &(pool->queue_lock));  
  135.         }  
  136.     }else{  
  137.         /* 等待队列长度减去1,并取出队列中的第一个元素 */  
  138.         pool->task_in_queue--;  
  139.         task = pool->queue_head;  
  140.         pool->queue_head = task->next;  
  141.         printf("thread 0x%lx received a task\n", pthread_self());  
  142.     }  
  143.     pthread_mutex_unlock(&(pool->queue_lock));  
  144.     return task;  
  145. }  
  146.   
  147. /********************************************************************* 
  148. *功能:        向线程池中添加一个任务 
  149. *参数:         
  150.             pool:线程池句柄 
  151.             process:任务处理函数 
  152.             arg:任务参数 
  153. *返回值:   0 
  154. *********************************************************************/  
  155. int pool_add_task(pool_t *pool, pool_task_f process, void *arg)  
  156. {  
  157.     enqueue_task(pool, process, arg);  
  158.     return 0;  
  159. }  
  160.   
  161. /********************************************************************* 
  162. *功能:        线程池服务程序 
  163. *参数:        略 
  164. *返回值:   略 
  165. *********************************************************************/  
  166. static void *pool_thread_server(void *arg)  
  167. {  
  168.     pool_t *pool = NULL;  
  169.       
  170.     pool = (pool_t *)arg;  
  171.     while(1){  
  172.         pool_task *task = NULL;  
  173.         task = dequeue_task(pool);  
  174.         /*调用回调函数,执行任务*/  
  175.         if(task != NULL){  
  176.             printf ("thread 0x%lx is busy\n", pthread_self());  
  177.             task->process(task->arg);  
  178.             free(task);  
  179.             task = NULL;  
  180.         }  
  181.     }  
  182.     /*这一句应该是不可达的*/  
  183.     pthread_exit(NULL);    
  184.     return NULL;  
  185. }  

下面是测试代码:

[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <unistd.h>  
  3.   
  4. #include "thread_pool.h"  
  5.   
  6. void *task_test(void *arg)  
  7. {  
  8.     printf("\t\tworking on task %d\n", (int)arg);  
  9.     sleep(1);           /*休息一秒,延长任务的执行时间*/  
  10.     return NULL;  
  11. }  
  12.   
  13. void thread_pool_demo(void)  
  14. {  
  15.     pool_t pool;  
  16.     int i = 0;  
  17.   
  18.     pool_init(&pool, 2);//初始化一个线程池,其中创建2个线程  
  19.     sleep(1);  
  20.     for(i = 0; i < 5; i++){  
  21.         sleep(1);  
  22.         pool_add_task(&pool, task_test, (void *)i);//添加一个任务  
  23.     }  
  24.     sleep(4);  
  25.   
  26.     pool_uninit(&pool);//删除线程池  
  27. }  
  28.   
  29. int main (int argc, char *argv[])  
  30. {    
  31.     thread_pool_demo();  
  32.     return 0;  
  33. }  

运行结果如下:




本教程示例代码下载请点此处。

转载地址:http://blog.csdn.net/lianghe_work/article/details/47747383

0 0
原创粉丝点击