Linux 下C语言简单实现线程池

转自:http://blog.csdn.net/wallwind/article/details/7669132


C语言简单实现线程池

前言

网上关于线程池的例子还是不少,简单明了的倒是比较少,看了网上的资料,打算借鉴网上的一些例子,自己实现以下。

线程的概念就不多说,首先说一下多线程的好处:多线程技术主要解决处理器单元内多个线程执行的问题,它可以显著减少处理器单元的闲置时间,增加处理器单元的吞吐能力。

那么为什么又需要线程池呢?

我们知道应用程序创建一个对象,然后销毁对象是很耗费资源的。创建线程,销毁线程,也是如此。因此,我们就预先生成一些线程,等到我们使用的时候在进行调度,于是,一些"池化资源"技术就这样的产生了。

 

线程池优点

下面使用网上资源验证线程池如何提高服务器性能的。

我所提到服务器程序是指能够接受客户请求并能处理请求的程序,而不只是指那些接受网络客户请求的网络服务器程序。

多线程技术主要解决处理器单元内多个线程执行的问题,它可以显著减少处理器单元的闲置时间,增加处理器单元的吞吐能力。但如果对多线程应用不当,会增加对单个任务的处理时间。可以举一个简单的例子:

假设在一台服务器完成一项任务的时间为T

     T1 创建线程的时间

      T2 在线程中执行任务的时间,包括线程间同步所需时间

      T3 线程销毁的时间              

显然T = T1+T2+T3。注意这是一个极度简化的假设。

可以看出T1,T3是多线程本身的带来的开销,我们渴望减少T1,T3所用的时间,从而减少T的时间。但一些线程的使用者并没有注意到这一点,所以在程序中频繁的创建或销毁线程,这导致T1和T3在T中占有相当比例。显然这是突出了线程的弱点(T1,T3),而不是优点(并发性)。

线程池技术正是关注如何缩短或调整T1,T3时间的技术,从而提高服务器程序性能的。它把T1,T3分别安排在服务器程序的启动和结束的时间段或者一些空闲的时间段,这样在服务器程序处理客户请求时,不会有T1,T3的开销了。

线程池不仅调整T1,T3产生的时间段,而且它还显著减少了创建线程的数目。在看一个例子:

假设一个服务器一天要处理50000个请求,并且每个请求需要一个单独的线程完成。我们比较利用线程池技术和不利于线程池技术的服务器处理这些请求时所产生的线程总数。在线程池中,线程数一般是固定的,所以产生线程总数不会超过线程池中线程的数目或者上限(以下简称线程池尺寸),而如果服务器不利用线程池来处理这些请求则线程总数为50000。一般线程池尺寸是远小于50000。所以利用线程池的服务器程序不会为了创建50000而在处理请求时浪费时间,从而提高效率。

这些都是假设,不能充分说明问题,下面我将讨论线程池的简单实现并对该程序进行对比测试,以说明线程技术优点及应用领域。

 

线程池的简单实现

一般一个简单线程池至少包含下列组成部分。

  1. 线程池管理器(ThreadPoolManager):用于创建并管理线程池
  2. 工作线程(WorkThread): 线程池中线程
  3. 任务接口(Task):每个任务必须实现的接口,以供工作线程调度任务的执行。
  4. 任务队列:用于存放没有处理的任务。提供一种缓冲机制。

 

下面是代码:

全局文件:

[cpp]  view plain copy
  1. /**********************************  
  2.  * @author     <a href="mailto:wallwind@yeah.net">wallwind@<span style="color:#000000;">yeah.net</span></a> 
  3.  * @date        2012/06/13 
  4.  * Last update: 2012/06/13 
  5.  * License:     LGPL 
  6.  *  
  7.  **********************************/  
  8.    
  9.  #ifndef _GLOBAL_H_  
  10.  #define _GLOBAL_H_  
  11.    
  12.  #include <sys/types.h>  
  13. #include <sys/time.h>  
  14. #include <unistd.h>             /* */  
  15. #include <stdarg.h>  
  16. #include <stddef.h>             /* offsetof() */  
  17. #include <stdio.h>  
  18. #include <stdlib.h>  
  19. #include <errno.h>  
  20. #include <string.h>  
  21. #include <signal.h>  
  22. #include <pwd.h>  
  23. #include <grp.h>  
  24. #include <dirent.h>  
  25. #include <glob.h>  
  26. #include <sys/vfs.h>            /* statfs() */  
  27.   
  28. #include <sys/uio.h>  
  29. #include <sys/stat.h>  
  30. #include <fcntl.h>  
  31.   
  32. #include <sys/wait.h>  
  33. #include <sys/mman.h>  
  34. #include <sys/resource.h>  
  35. #include <sched.h>  
  36.   
  37. #include <sys/socket.h>  
  38. #include <netinet/in.h>  
  39. #include <netinet/tcp.h>        /* TCP_NODELAY, TCP_CORK */  
  40. #include <arpa/inet.h>  
  41. #include <netdb.h>  
  42. #include <sys/un.h>  
  43.   
  44. #include <time.h>               /* tzset() */  
  45. #include <malloc.h>             /* memalign() */  
  46. #include <limits.h>             /* IOV_MAX */  
  47. #include <sys/ioctl.h>  
  48. #include <sys/sysctl.h>  
  49. #include <crypt.h>  
  50. #include <sys/utsname.h>        /* uname() */  
  51. #include <semaphore.h>  
  52.   
  53. #include <sys/epoll.h>  
  54. #include <poll.h>  
  55. #include <sys/syscall.h>  
  56. #include <pthread.h>  
  57.  #endif  


thread.c文件

[cpp]  view plain copy
  1. /**********************************  
  2.  * @author      wallwind@yeah.net 
  3.  * @date        2012/06/13 
  4.  * Last update: 2012/06/13 
  5.  * License:     LGPL 
  6.  *  
  7.  **********************************/  
  8.    
  9.    
  10.    
  11.  #ifndef _THPOOL_  
  12.  #define _THPOOL_  
  13.    
  14.  #include "global.h"  
  15.  /** 
  16.     定义一个任务节点 
  17.  **/  
  18.  typedef void* (*FUNC)(void* arg);  
  19.    
  20.    
  21.  typedef struct _thpool_job_t{  
  22. //  void* (*function)(void* arg);    //函数指针  
  23.     FUNC             function;  
  24.     void*                   arg;     //函数参数。  
  25.     struct _thpool_job_t* prev;     // 指向上一个节点  
  26.     struct _thpool_job_t* next;     //指向下一个节点  
  27.  } thpool_job_t;  
  28.    
  29.  /** 
  30.     定义一个工作队列 
  31.  **/  
  32.    
  33. typedef struct _thpool_job_queue{  
  34.     thpool_job_t*    head;            //队列头指针   
  35.     thpool_job_t*    tail;             // 队列末尾指针  
  36.     int              jobN;                    //任务数  
  37.     sem_t*           queueSem;            //x信号量  
  38. }thpool_jobqueue;   
  39.    
  40.  /** 
  41.     线程池 
  42.  **/  
  43.    
  44.  typedef struct _thpool_t{  
  45.     pthread_t*      threads;    线程指针数  
  46.     int             threadsN;     线程数  
  47.     thpool_jobqueue* jobqueue;   // 指向队列指针  
  48.  }thpool_t;  
  49.    
  50.  typedef struct thread_data{                              
  51.     pthread_mutex_t *mutex_p;  
  52.     thpool_t        *tp_p;  
  53. }thread_data;  
  54.   
  55.  //初始化线程池内部的线程数  
  56. thpool_t*  thpool_init(int threadN);  
  57.   
  58. void thpool_thread_do(thpool_t* tp_p);  
  59.   
  60. int thpool_add_work(thpool_t* tp_p, void *(*function_p)(void*), void* arg_p);  
  61.   
  62. void thpool_destroy(thpool_t* tp_p);  
  63.   
  64.   
  65.   
  66. int thpool_jobqueue_init(thpool_t* tp_p);  
  67.   
  68.   
  69.   
  70. void thpool_jobqueue_add(thpool_t* tp_p, thpool_job_t* newjob_p);  
  71.   
  72. int thpool_jobqueue_removelast(thpool_t* tp_p);  
  73.   
  74. thpool_job_t* thpool_jobqueue_peek(thpool_t* tp_p);  
  75.   
  76. void thpool_jobqueue_empty(thpool_t* tp_p);  
  77.   
  78.  #endif  

 

thread.c

[cpp]  view plain copy
  1. /**********************************  
  2.  * @author     wallwind@yeah.net 
  3.  * @date        2012/06/13 
  4.  * Last update: 2012/06/13 
  5.  * License:     LGPL 
  6.  *  
  7.  **********************************/  
  8.  #include "global.h"  
  9.  #include "Thread.h"  
  10.  #include <errno.h>  
  11.    
  12.  static int thpool_keepalive = 1;  
  13.    
  14.  /* 创建互斥量,并初始化 */  
  15.   pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; /* used to serialize queue access */  
  16.    
  17. thpool_t*  thpool_init(int threadN)  
  18. {  
  19.     thpool_t* thpool;  
  20.     if(!threadN || threadN < 1)  
  21.         threadN = 1;  
  22.     ///分配线程池内存  
  23.     thpool = (thpool_t*) malloc(sizeof(thpool_t));  
  24.     if(thpool ==NULL)  
  25.     {  
  26.         printf("malloc thpool_t error");  
  27.         return NULL;  
  28.     }  
  29.     //分配线程数  
  30.     thpool->threadsN = threadN;  
  31.     thpool->threads =(pthread_t*) malloc(threadN*sizeof(pthread_t));  
  32.     if(thpool->threads == NULL)  
  33.     {  
  34.         printf("malloc thpool->threads error");  
  35.         return NULL;  
  36.     }  
  37.     if(thpool_jobqueue_init(thpool))  
  38.         return -1;  
  39.   
  40.     thpool->jobqueue->queueSem =(sem_t*)malloc(sizeof(sem_t));  
  41.     sem_init(thpool->jobqueue->queueSem,0,1);  
  42.     int t;  
  43.     for(t = 0;t< threadN ;t++)  
  44.     {  
  45.         pthread_create(&(thpool->threads[t]),NULL,(void *)thpool_thread_do,(void*)thpool);  
  46.     }  
  47.       
  48.     return thpool;  
  49. }  
  50.   
  51. void thpool_destroy(thpool_t* tp_p)  
  52. {  
  53.     int i ;  
  54.     thpool_keepalive = 0;  
  55.       
  56.     for(i = 0;i < (tp_p->threadsN); i++)  
  57.     {  
  58.         if(sem_post(tp_p->jobqueue->queueSem))  
  59.         {  
  60.             fprintf(stderr, "thpool_destroy(): Could not bypass sem_wait()\n");  
  61.         }  
  62.   
  63.     }  
  64.     if(sem_post(tp_p->jobqueue->queueSem)!=0)  
  65.     {  
  66.         fprintf(stderr, "thpool_destroy(): Could not destroy semaphore\n");  
  67.     }  
  68.     for(i = 0;i < (tp_p->threadsN); i++)  
  69.     {  
  70.         pthread_join(tp_p->threads[i],NULL);  
  71.     }  
  72.     thpool_jobqueue_empty(tp_p);  
  73.       
  74.     free(tp_p->threads);  
  75.     free(tp_p->jobqueue->queueSem);  
  76.     free(tp_p->jobqueue);  
  77.     free (tp_p);  
  78.       
  79. }  
  80. 对双向队列初始化  
  81. /* Initialise queue */  
  82. int thpool_jobqueue_init(thpool_t* tp_p){  
  83.     tp_p->jobqueue=(thpool_jobqueue*)malloc(sizeof(thpool_jobqueue));      /* MALLOC job queue */  
  84.     if (tp_p->jobqueue==NULL) return -1;  
  85.     tp_p->jobqueue->tail=NULL;  
  86.     tp_p->jobqueue->head=NULL;  
  87.     tp_p->jobqueue->jobN=0;  
  88.     return 0;  
  89. }  
  90.   
  91.   
  92. void thpool_thread_do(thpool_t* tp_p)  
  93. {  
  94.     while(thpool_keepalive ==1)  
  95.     {  
  96.         if(sem_wait(tp_p->jobqueue->queueSem)) ///线程阻塞,等待通知 直到消息队列有数据  
  97.         {  
  98.             perror("thpool_thread_do(): Waiting for semaphore");  
  99.             exit(1);  
  100.         }  
  101.         if(thpool_keepalive)  
  102.         {  
  103.             //(void*)(*function)(void *arg);  
  104.             FUNC function;  
  105.             void* arg_buff;  
  106.             thpool_job_t*  job_p;  
  107.               
  108.             pthread_mutex_lock(&mutex);  
  109.              job_p = thpool_jobqueue_peek(tp_p);  
  110.             function = job_p->function;  
  111.             arg_buff = job_p->arg;  
  112.             if(thpool_jobqueue_removelast(tp_p))  
  113.                 return ;  
  114.             pthread_mutex_unlock(&mutex);  
  115.             function(arg_buff);   //运行 你的方法。  
  116.             free(job_p);         释放掉。  
  117.         }  
  118.         else  
  119.         {  
  120.             return ;  
  121.         }  
  122.               
  123.     }  
  124.     return ;  
  125. }  
  126.   
  127. //得到第一个队列的一个节点  
  128. thpool_job_t* thpool_jobqueue_peek(thpool_t* tp_p)  
  129. {  
  130.     return tp_p->jobqueue->tail;  
  131. }  
  132. /删除队列的最后一个节点  
  133. int thpool_jobqueue_removelast(thpool_t* tp_p)  
  134. {  
  135.     if(tp_p ==NULL)  
  136.         return -1;  
  137.     thpool_job_t* theLastJob;  
  138.     theLastJob = tp_p->jobqueue->tail;  
  139.     switch(tp_p->jobqueue->jobN)  
  140.     {  
  141.         case 0:  
  142.             return -1;  
  143.         case 1:  
  144.             tp_p->jobqueue->head =NULL;  
  145.             tp_p->jobqueue->tail =NULL;  
  146.             break;  
  147.         default:  
  148.             theLastJob->prev->next = NULL;  
  149.             tp_p->jobqueue->tail = theLastJob->prev;  
  150.                   
  151.     }  
  152.     (tp_p->jobqueue->jobN)--;  
  153.     int reval;  
  154.     sem_getvalue(tp_p->jobqueue->queueSem,&reval);  
  155.     return 0;     
  156. }  
  157.   
  158. void thpool_jobqueue_add(thpool_t* tp_p, thpool_job_t* newjob_p)  
  159. {  
  160.     newjob_p->next = NULL;  
  161.     newjob_p->prev = NULL;  
  162.     thpool_job_t* oldFirstJob;  
  163.     oldFirstJob = tp_p->jobqueue->head;  
  164.       
  165.     switch(tp_p->jobqueue->jobN)  
  166.     {  
  167.         case 0:  
  168.             tp_p->jobqueue->head = newjob_p;  
  169.             tp_p->jobqueue->tail = newjob_p;  
  170.             break;  
  171.         default:  
  172.             oldFirstJob->prev = newjob_p;  
  173.             newjob_p->next = oldFirstJob;  
  174.             tp_p->jobqueue->head = newjob_p;  
  175.       
  176.     }  
  177.     (tp_p->jobqueue->jobN)++;  
  178.     sem_post(tp_p->jobqueue->queueSem);  
  179.       
  180.     int reval;  
  181.     sem_getvalue(tp_p->jobqueue->queueSem,&reval);  
  182.     return;  
  183. }  
  184.   
  185. /将消息加入线程池  
  186. int thpool_add_work(thpool_t* tp_p, void* (*function_p)(void*), void* arg_p)  
  187. {  
  188.     thpool_job_t* newjob;  
  189.     newjob = (thpool_job_t*) malloc(sizeof(thpool_job_t));  
  190.       
  191.     if(newjob ==NULL)  
  192.     {  
  193.         fprintf(stderr, "thpool_add_work(): Could not allocate memory for new job\n");  
  194.         exit(1);  
  195.     }  
  196.     newjob ->function = function_p;  
  197.     newjob ->arg      = arg_p;  
  198.     pthread_mutex_lock(&mutex);  
  199.     thpool_jobqueue_add(tp_p,newjob);  
  200.     pthread_mutex_unlock(&mutex);       
  201.     return 0;  
  202. }  
  203.   
  204. ///清空队列  
  205. void thpool_jobqueue_empty(thpool_t* tp_p)  
  206. {  
  207.     thpool_job_t* curjob;  
  208.     curjob = tp_p->jobqueue->tail;  
  209.       
  210.     while(tp_p->jobqueue->jobN)  
  211.     {  
  212.         tp_p->jobqueue->tail = curjob->prev;  
  213.         free (curjob);  
  214.         curjob = tp_p->jobqueue->tail;  
  215.         (tp_p->jobqueue->jobN)--;  
  216.     }  
  217.     tp_p->jobqueue->head = NULL;  
  218.     tp_p->jobqueue->tail = NULL;  
  219. }  


下面是mian函数文件

[cpp]  view plain copy
  1. /**********************************  
  2.  * @author      wallwind@yeah.net 
  3.  * @date        2012/06/13 
  4.  * Last update: 2012/06/13 
  5.  * License:     LGPL 
  6.  *  
  7.  **********************************/  
  8.   
  9. #include "global.h"  
  10. #include "Thread.h"  
  11.   
  12.     void* task1()  
  13.     {  
  14.         printf("# Thread working: %u\n", (int)pthread_self());  
  15.         printf("  Task 1 running..\n");  
  16.     }  
  17.   
  18.   
  19.     /* Some arbitrary task 2 */  
  20.     void* task2(int a)  
  21.     {  
  22.         printf("# Thread working: %u\n", (int)pthread_self());  
  23.         printf("  Task 2 running..\n");  
  24.         printf("%d\n", a);  
  25.     }  
  26. int main()  
  27. {  
  28.     printf("~~~~~~~~~~~");  
  29.     thpool_t* thpool;  
  30.     int i;  
  31.     thpool = thpool_init(5);  
  32.     puts("Adding 20 tasks to threadpool");  
  33.     int a=54;  
  34.     for (i=0; i<20; i++){  
  35.         thpool_add_work(thpool, (void*)task1, NULL);  
  36.         thpool_add_work(thpool, (void*)task2, (void*)a);  
  37.     };  
  38.   
  39.   
  40.     puts("Will kill threadpool");  
  41.     thpool_destroy(thpool);  
  42.       
  43. }  


在linux下写程序少不了makefile文件。于是我自己写了一个比较通用的makefile文件。仅供大家参考

makefile 代码

[cpp]  view plain copy
  1. SRCS=$(wildcard *.c)  
  2.   
  3. OBJS=$(SRCS:.c=.o)  
  4.   
  5. CC=gcc  
  6.   
  7. INCLUDES=-I/  
  8.   
  9. LIBS=-L/ -lpthread  
  10.   
  11. CCFLAGS = -g -Wall -O0  
  12.   
  13. cThreadPool : $(OBJS)  
  14.   
  15.         $(CC) $^ -o $@ $(INCLUDES) $(LIBS)  
  16.   
  17. %.o : %.cpp  
  18.   
  19.         $(CC) -c $<$(CCFLAGS)  
  20.   
  21.   
  22. clean:  
  23.   
  24.         rm *.o  
  25.   
  26.         .PHONY:clean  

运行效果如下图

[cpp]  view plain copy
  1. ./test  
  2. Created thread 0 in pool   
  3. Created thread 1 in pool   
  4. Created thread 2 in pool   
  5. Created thread 3 in pool   
  6. Adding 20 tasks to threadpool  
  7. # Thread working: 3086773136  
  8.   Task 1 running..  
  9. # Thread working: 3076283280  
  10.   Task 2 running..  
  11. 54  
  12. # Thread working: 3086773136  
  13.   Task 1 running..  
  14. # Thread working: 3086773136  
  15.   Task 2 running..  
  16. 54  
  17. # Thread working: 3076283280  
  18.   Task 1 running..  
  19. # Thread working: 3086773136  
  20.   Task 2 running..  
  21. 54  
  22. # Thread working: 3076283280  
  23.   Task 1 running..  
  24. # Thread working: 3086773136  
  25.   Task 2 running..  
  26. 54  
  27. # Thread working: 3076283280  
  28.   Task 1 running..  
  29. # Thread working: 3086773136  
  30.   Task 2 running..  
  31. 54  
  32. # Thread working: 3076283280  
  33.   Task 1 running..  
  34. # Thread working: 3086773136  
  35.   Task 2 running..  
  36. 54  
  37. # Thread working: 3076283280  
  38.   Task 1 running..  
  39. # Thread working: 3086773136  
  40.   Task 2 running..  
  41. 54  
  42. # Thread working: 3076283280  
  43.   Task 1 running..  
  44. # Thread working: 3086773136  
  45.   Task 2 running..  
  46. 54  
  47. # Thread working: 3076283280  
  48.   Task 1 running..  
  49. # Thread working: 3086773136  
  50.   Task 2 running..  
  51. 54  
  52. # Thread working: 3076283280  
  53.   Task 1 running..  
  54. # Thread working: 3086773136  
  55.   Task 2 running..  
  56. 54  
  57. Will kill threadpool  


线程池也是参考了别人的。

 

更多文章欢迎访问:http://blog.csdn.net/wallwind 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值