linux的多任务编程-线程池

简介

在嵌入式系统环境下,由于系统资源和任务的特点,多线程成了实现多任务处理的重要方式.在一些常见的应用环境中,如Web服务器,Email服务器以及数据库服务器等都具有一个共同点:单位时间内必须处理很多并发的连接请求,但处理时间却相对较短.传统多线程方案中我们采用的服务器模型则是一旦接受到请求之后,即创建一个新的线程,由该线程执行任务.任务执行完毕后,线程退出,这就是是"即时创建,即时销毁"的策略.尽管与创建进程相比,创建线程的时间已经大大的缩短,但是如果提交给线程的任务是执行时间较短,而且执行次数及其频繁,那么服务器将处于不停的创建线程,销毁线程的状态.
线程池是采用多线程解决方案来提高系统性能的一个最为出色的模型,它通过预创建一定数量的工作线程来对系统进行并发处理,使得系统的运行效率提高.因为线程池能使得系统采用较为轻量的,可控的系统资源实现系统并发处理能力的最大化,所以许多应用软件都采用了线程池模型.
除此之外,线程是能够限制创建的进程个数.通常线程池所允许的并发线程具有上界的,如果同时需要并发的线程数超过上界,那么一部分线程将等待.而传统方案中,如果同时请求数据为200,那么最坏情况下,系统可能需要产生200个线程.尽管这不是一个很大的数目,但是也有系统达不到这个要求.
线程池模型有许多种,常见的有三种:任务队列控制的线程池模型,工作线程控制的线程池模型,主控线程控制的线程池模型.本文将给出一中任务队列控制的线程池模型的具体实现.
任务队列控制的线程池模型是通过任务队列来对线程池进行并发调度,如下图所示.线程池是由预创建的一个任务队列和一组工作线程组成,其中任务队列中存放工作对象.线程池启动后,工作线程将采用轮询的方式从任务队列中获取任务对象,由于初始化时任务队列中不存在任务对象,这时的信号量为0,所有的工作线程都处于阻塞状态.主控线程将任务对象放入任务队列中,并将信号量加1,这样信号量就会唤醒一个阻塞中的工作线程(操作系统层面决定唤醒哪个阻塞的工作线程).工作线程唤醒后从任务队列中获取一个任务对象并执行该任务,执行完后,工作线程将再次访问信号量,如果信号信号量大于0,那么工作线程将继续从任务队列中获取任务对象并执行,知道信号量等于0,这时的工作线程将再次被阻塞.


任务队列控制的线程模型主要是通过任务队列上的信号来控制线程池中的线程调度.

线程池的实现

本例程共由5个文件构成:tpool.h,tpool.c,log.c,log.h,testpool.c.其中tpool.h,tpool.c是实现线程池的核心文件,在tpool.h中定义了线程池和工作线程的数据结构及创建线程池和添加工作线程等方法,tpool.c中为具体的实现代码.log.c,log.h提供了一种记录文件的生成手段,能在文件中记录自定义的信息.testpool.c为线程池的测试程序.

该例子由多个源文件组成,编译命令如下:
gcc -g -pthread -o testpool testpool.c tpool.c log.c

下面给出这个例子的源代码,首先是线程池的定义文件tpool.h:

[cpp]  view plain  copy
 print ?
  1. /*------------------------------------------------------------------------- 
  2.  * tpool.h – 线程池定义 
  3.  * ------------------------------------------------------------------------- 
  4.  */  
  5. #ifndef _TPOOL_H_  
  6. #define _TPOOL_H_  
  7. #include  <stdio.h>  
  8. #include  <pthread.h>  
  9. /*工作线程链表*/  
  10. typedef struct tpool_work  
  11. {  
  12.   void (*handler_routine)();            /*任务函数指针*/  
  13.   void *arg;                        /*任务函数参数*/  
  14.   struct tpool_work *next;              /*下一个任务链表*/  
  15. } tpool_work_t;  
  16. /*线程池结构体*/  
  17. typedef struct tpool  
  18. {  
  19.   int num_threads;                  /*最大线程数*/  
  20.   int max_queue_size;               /*最大任务链表数*/  
  21.   int do_not_block_when_full;           /*当链表满时是否阻塞*/  
  22.   pthread_t *threads;               /*线程指针*/  
  23.   int cur_queue_size;  
  24.   tpool_work_t *queue_head;         /*链表头*/  
  25.   tpool_work_t *queue_tail;         /*链表尾*/  
  26.   pthread_mutex_t queue_lock;       /*链表互斥量*/  
  27.   pthread_cond_t queue_not_full;        /*链表条件量-未满*/  
  28.   pthread_cond_t queue_not_empty;   /*链表条件量-非空*/  
  29.   pthread_cond_t queue_empty;       /*链表条件量-空*/  
  30.   int queue_closed;  
  31.   int shutdown;  
  32. } tpool_t;  
  33. /* 初始化连接池 */  
  34. extern tpool_t *tpool_init(int num_worker_threads,\  
  35.     int max_queue_size, int do_not_block_when_full);  
  36. /* 添加一个工作线程 */  
  37. extern int tpool_add_work(tpool_t *pool, void  (*routine)(), void *arg);  
  38. /* 清除线程池*/  
  39. extern int tpool_destroy(tpool_t *pool, int finish);  
  40. #endif /* _TPOOL_H_ */  
在这个文件中定义了线程池的结构,工作线程函数的原型以及线程池的基本操作.线面给出的tpool.c是线程池的实现.函数tpool_init完成了线程池的初始化操作,包括对内存的设置,对线程属性的设置和池中线程的预创建.

[cpp]  view plain  copy
 print ?
  1. /* ------------------------------------------------------------------------- 
  2.  * tpool.c – 线程池的实现 
  3.  * ------------------------------------------------------------------------- 
  4.  */  
  5. #include  <stdio.h>  
  6. #include  <stdlib.h>  
  7. #include  <string.h>   
  8. #include  <pthread.h>  
  9. #include "tpool.h"  
  10. #include "log.h"  
  11. /* 工作线程 */  
  12. void *tpool_thread(void *tpool);  
  13. /***************线程池初始化*****************************/  
  14. tpool_t *tpool_init(int num_worker_threads,\    /*线程池线程个数*/  
  15.                   int max_queue_size, \     /*最大任务数*/  
  16.               int do_not_block_when_full)   /*是否阻塞任务满的时候*/  
  17. {  
  18.     int i, rtn;  
  19.     tpool_t *pool;   
  20.     lprintf(log, INFO, "init pool begin ...\n");  
  21.     /* 创建线程池结构体 */  
  22.     if((pool = (struct tpool *)malloc(sizeof(struct tpool))) == NULL)   
  23.     {  
  24.         lprintf(log, FATAL, "Unable to malloc() thread pool!\n");  
  25.         return NULL;  
  26.     }  
  27.     /* 设置线程池架构体成员 */  
  28.     pool->num_threads = num_worker_threads;                      /*工作线程个数*/  
  29.     pool->max_queue_size = max_queue_size;                       /*任务链表最大长度*/  
  30.     pool->do_not_block_when_full = do_not_block_when_full;       /*任务链表满时是否等待*/  
  31.     /* 生成线程池缓存 */  
  32.     if((pool->threads = (pthread_t *)malloc(sizeof(pthread_t)*num_worker_threads)) == NULL)   
  33.     {  
  34.         lprintf(log, FATAL,"Unable to malloc() thread info array\n");  
  35.         return NULL;   
  36.     }  
  37.     /* 初始化任务链表 */  
  38.     pool->cur_queue_size = 0;  
  39.     pool->queue_head = NULL;  
  40.     pool->queue_tail = NULL;  
  41.     pool->queue_closed = 0;  
  42.     pool->shutdown = 0;  
  43.     /* 初始化互斥变量,条件变量 用于线程之间的同步 */  
  44.     if((rtn = pthread_mutex_init(&(pool->queue_lock),NULL)) != 0)   
  45.     {  
  46.         lprintf(log,FATAL,"pthread_mutex_init %s",strerror(rtn));  
  47.         return NULL;  
  48.     }  
  49.     if((rtn = pthread_cond_init(&(pool->queue_not_empty),NULL)) != 0)   
  50.     {  
  51.         lprintf(log,FATAL,"pthread_cond_init %s",strerror(rtn));  
  52.         return NULL;  
  53.     }  
  54.     if((rtn = pthread_cond_init(&(pool->queue_not_full),NULL)) != 0)   
  55.     {  
  56.         lprintf(log,FATAL,"pthread_cond_init %s",strerror(rtn));  
  57.         return NULL;  
  58.     }  
  59.     if((rtn = pthread_cond_init(&(pool->queue_empty),NULL)) != 0)   
  60.     {  
  61.         lprintf(log,FATAL,"pthread_cond_init %s",strerror(rtn));  
  62.         return NULL;  
  63.     }  
  64.     /* 创建所有的线程 */  
  65.     for(i = 0; i != num_worker_threads; i++)   
  66.     {  
  67.         if( (rtn=pthread_create(&(pool->threads[i]),NULL,tpool_thread,(void*)pool)) != 0)   
  68.         {  
  69.             lprintf(log,FATAL,"pthread_create %s\n",strerror(rtn));  
  70.             return NULL;   
  71.         }  
  72.         lprintf(log, INFO, "init pthread  %d!\n",i);  
  73.     }  
  74.     lprintf(log, INFO, "init pool end!\n");  
  75.     return pool;  
  76. }  
函数tpool_add_work为线程池添加了一个工作线程.因为预创建的线程是不能做任何工作的,只有分配了适当的任务后,才会使预创建的线程真正的工作起来.

[cpp]  view plain  copy
 print ?
  1. int tpool_add_work(tpool_t *pool,   \           /*线程池指针*/  
  2.                     void (*routine)(void *),\   /*工作线程函数指针*/  
  3.                     void *arg)                  /*工作线程函数参数*/  
  4. {  
  5.     int rtn;  
  6.     tpool_work_t *workp; /*当前工作线程*/  
  7.     if((rtn = pthread_mutex_lock(&pool->queue_lock)) != 0)  
  8.     {  
  9.         lprintf(log,FATAL,"pthread mutex lock failure\n");  
  10.         return -1;  
  11.     }  
  12.     /* 采取独占的形式访问任务链表 */  
  13.     if((pool->cur_queue_size == pool->max_queue_size) && \  
  14.             (pool->do_not_block_when_full))   
  15.     {  
  16.         if((rtn = pthread_mutex_unlock(&pool->queue_lock)) != 0)  
  17.         {  
  18.             lprintf(log,FATAL,"pthread mutex lock failure\n");  
  19.             return -1;  
  20.         }  
  21.         return -1;  
  22.     }  
  23.     /* 等待任务链表为新线程释放空间 */  
  24.     while((pool->cur_queue_size == pool->max_queue_size) &&  
  25.             (!(pool->shutdown || pool->queue_closed)))   
  26.    {  
  27.         if((rtn = pthread_cond_wait(&(pool->queue_not_full),  
  28.                         &(pool->queue_lock)) ) != 0)   
  29.         {  
  30.             lprintf(log,FATAL,"pthread cond wait failure\n");  
  31.             return -1;  
  32.         }  
  33.     }  
  34.     if(pool->shutdown || pool->queue_closed)   
  35.     {  
  36.         if((rtn = pthread_mutex_unlock(&pool->queue_lock)) != 0)    
  37.         {  
  38.             lprintf(log,FATAL,"pthread mutex lock failure\n");  
  39.             return -1;  
  40.         }  
  41.         return -1;  
  42.     }  
  43.     /* 分配工作线程结构体 */  
  44.     if((workp = (tpool_work_t *)malloc(sizeof(tpool_work_t))) == NULL)   
  45.     {  
  46.         lprintf(log,FATAL,"unable to create work struct\n");  
  47.         return -1;  
  48.     }  
  49.     workp->handler_routine = routine;  
  50.     workp->arg = arg;  
  51.     workp->next = NULL;  
  52.     if(pool->cur_queue_size == 0)   
  53.     {  
  54.         pool->queue_tail = pool->queue_head = workp;  
  55.         if((rtn = pthread_cond_broadcast(&(pool->queue_not_empty))) != 0)  
  56.         {  
  57.             lprintf(log,FATAL,"pthread broadcast error\n");  
  58.             return -1;  
  59.         }  
  60.     }  
  61.     else   
  62.     {  
  63.         pool->queue_tail->next = workp;  
  64.         pool->queue_tail = workp;  
  65.     }  
  66.     pool->cur_queue_size++;  
  67.     /* 释放对任务链表的独占 */  
  68.     if((rtn = pthread_mutex_unlock(&pool->queue_lock)) != 0)   
  69.     {  
  70.         lprintf(log,FATAL,"pthread mutex lock failure\n");  
  71.         return -1;  
  72.     }  
  73.     return 0;  
  74. }  
当线程池退出后,需要释放所用的资源,包括以下五个步骤:

  1. 设置线程退出标记;
  2. 禁止添加新任务到任务链表;
  3. 设置线程池销毁标记;
  4. 等待所有已经建立的线程退出;
  5. 释放线程池所占的内存空间.
[cpp]  view plain  copy
 print ?
  1. int tpool_destroy(tpool_t *pool, int finish)  
  2. {  
  3.     int i, rtn;  
  4.     tpool_work_t *cur;   /*当前工作线程*/  
  5.     lprintf(log, INFO, "destroy pool begin!\n");  
  6.     /* 释放对任务链表的独占 */  
  7.     if((rtn = pthread_mutex_lock(&(pool->queue_lock))) != 0)    
  8.     {  
  9.         lprintf(log,FATAL,"pthread mutex lock failure\n");  
  10.         return -1;  
  11.     }  
  12.     /* 第一步,设置线程退出标记 */  
  13.     lprintf(log, INFO, "destroy pool begin 1!\n");  
  14.     if(pool->queue_closed || pool->shutdown)   
  15.     {  
  16.         if((rtn = pthread_mutex_unlock(&(pool->queue_lock))) != 0)   
  17.         {  
  18.             lprintf(log,FATAL,"pthread mutex lock failure\n");  
  19.             return -1;  
  20.         }  
  21.         return 0;  
  22.     }  
  23.     /* 第二步,禁止新任务加入任务链表 */  
  24.     lprintf(log, INFO, "destroy pool begin 2!\n");  
  25.     pool->queue_closed = 1;  
  26.     if(finish)   
  27.     {  
  28.         while(pool->cur_queue_size != 0)   
  29.         {  
  30.             if((rtn = pthread_cond_wait(&(pool->queue_empty),&(pool->queue_lock))) != 0)   
  31.             {  
  32.                 lprintf(log,FATAL,"pthread_cond_wait %d\n",rtn);  
  33.                 return -1;  
  34.             }  
  35.         }  
  36.     }  
  37.     /* 第三步,设置线程池销毁标记 */  
  38.     lprintf(log, INFO, "destroy pool begin 3!\n");  
  39.     pool->shutdown = 1;  
  40.     if((rtn = pthread_mutex_unlock(&(pool->queue_lock))) != 0)   
  41.     {  
  42.         lprintf(log,FATAL,"pthread mutex unlock failure\n");  
  43.         return -1;  
  44.     }  
  45.     /* 第四步,等待所有已建立的线程退出 */  
  46.     lprintf(log, INFO, "destroy pool begin 4!\n");  
  47.     if((rtn = pthread_cond_broadcast(&(pool->queue_not_empty))) != 0)   
  48.     {  
  49.         lprintf(log,FATAL,"pthread_cond_boradcast %d\n",rtn);  
  50.         return -1;  
  51.     }  
  52.     if((rtn = pthread_cond_broadcast(&(pool->queue_not_full)))  != 0)   
  53.     {  
  54.         lprintf(log,FATAL,"pthread_cond_boradcast %d\n",rtn);  
  55.         return -1;  
  56.     }  
  57.     for(i = 0; i < pool->num_threads; i++)   
  58.     {  
  59.         if((rtn = pthread_join(pool->threads[i],NULL)) != 0)  
  60.         {  
  61.             lprintf(log,FATAL,"pthread_join %d\n",rtn);  
  62.             return -1;  
  63.         }  
  64.     }  
  65.     /* 第五步,释放线程池所占的内存空间 */  
  66.     free(pool->threads);  
  67.     while(pool->queue_head != NULL)   
  68.     {  
  69.         cur = pool->queue_head->next;  
  70.         pool->queue_head = pool->queue_head->next;  
  71.         free(cur);  
  72.     }  
  73.     free(pool);  
  74.     lprintf(log, INFO, "destroy pool end!\n");  
  75.     return 0;  
  76. }  
函数tpool_thread定义了工作线程的函数,其中真正与实际任务有关的只有一行代码:
[cpp]  view plain  copy
 print ?
  1. (*(my_work->handler_routine))(my_work->arg);   
即执行my_work->handler_routine指针指向的函数,并传入参数my_work->arg.其他的步骤都是为执行这个任务而进行的各种设置和准备.
[cpp]  view plain  copy
 print ?
  1. void *tpool_thread(void *tpool)   
  2. {  
  3.     tpool_work_t *my_work;  
  4.     tpool_t *pool = (struct tpool *)tpool;  
  5.   
  6.     for(;;)  
  7.     {/* 线程内循环 */  
  8.         pthread_mutex_lock(&(pool->queue_lock));     
  9.        /* 如果任务列表为0,并且线程池没有关闭,则一直等待,直到任务到来为止  */  
  10.        while((pool->cur_queue_size == 0) && (!pool->shutdown))   
  11.        {  
  12.             pthread_cond_wait(&(pool->queue_not_empty), &(pool->queue_lock));  
  13.         }  
  14.         /* 线程池是否已经关闭,如果线程池关闭则线程自己主动关闭 */  
  15.         if(pool->shutdown)  
  16.         {  
  17.             pthread_mutex_unlock(&(pool->queue_lock));  
  18.             pthread_exit(NULL);      /*线程退出状态为空,主线程不捕获各副线程状态*/  
  19.         }  
  20.         my_work = pool->queue_head;    
  21.         pool->cur_queue_size--;  
  22.         /*将任务链表头部去掉,改任务正在处理中*/  
  23.         if(pool->cur_queue_size == 0)      
  24.             pool->queue_head = pool->queue_tail = NULL;  
  25.         else  
  26.             pool->queue_head = my_work->next;  
  27.         /* 任务链表还没有满 */   
  28.         if((!pool->do_not_block_when_full) &&\  
  29.                 (pool->cur_queue_size == (pool->max_queue_size - 1)))   
  30.         {  
  31.             pthread_cond_broadcast(&(pool->queue_not_full));  
  32.         }  
  33.         /*任务链表为空*/  
  34.         if(pool->cur_queue_size == 0)   
  35.         {  
  36.             pthread_cond_signal(&(pool->queue_empty));  
  37.         }  
  38.         pthread_mutex_unlock(&(pool->queue_lock));  
  39.         /*启动线程业务处理逻辑*/  
  40.         (*(my_work->handler_routine))(my_work->arg);   
  41.         free(my_work);  
  42.     }  
  43.     return(NULL);  
  44. }  

工作状态的记录

为了便于记录线程池的工作状态,还实现了一个记录服务器.该记录服务器实现了一中类似syslog的日志功能,总共就三个函数,使用十分简单.
log.h是该记录服务器的头文件.

[cpp]  view plain  copy
 print ?
  1. /* ------------------------------------------------------------------------- 
  2.  * log.h 记录函数定义 
  3.   * ------------------------------------------------------------------------- 
  4.  */  
  5. #ifndef __LOG_H  
  6. #define __LOG_H  
  7. #include <stdio.h>  
  8. #include <semaphore.h>  
  9. /*记录的最大长度*/  
  10. #define LOGLINE_MAX 1024  
  11. /*记录的等级*/  
  12. #define DEBUG 1  
  13. #define INFO  2  
  14. #define WARN  3  
  15. #define ERROR 4  
  16. #define FATAL 5  
  17. /*记录的类型*/  
  18. #define LOG_TRUNC   1<<0  
  19. #define LOG_NODATE  1<<1  
  20. #define LOG_NOLF    1<<2  
  21. #define LOG_NOLVL   1<<3  
  22. #define LOG_DEBUG   1<<4  
  23. #define LOG_STDERR  1<<5  
  24. #define LOG_NOTID   1<<6  
  25. typedef struct   
  26. {  
  27.     int fd;  
  28.     sem_t sem;  
  29.     int flags;  
  30. } log_t;  
  31. /*  
  32. * 功能描述: 记录打印函数,将记录打印至记录文件logfile。 
  33.  * 参数:      log_t - log_open()函数的返回值 
  34. *           level - 可以是: DEBUG, INFO, WARN, ERROR, FATAL 
  35.  *          fmt  - 记录的内容,格式同printf()函数 
  36. * 返回值:  成功返回0,失败返回-1 
  37. */  
  38. int lprintf( log_t *log, unsigned int level, char *fmt, ... );  
  39. /* 
  40.  * 功能描述: 初始化记录文件the logfile 
  41.  *参数:   fname - 记录文件logfile的文件名 
  42.  *      flags    -  记录格式的选项 
  43.  *          LOG_TRUNC  -    截断打开的记录文件 
  44.  *          LOG_NODATE -    忽略记录中的每一行 
  45.  *          LOG_NOLF    -   自动为每条记录新开一行. 
  46.  *          LOG_NOLVL   - 不记录消息的等级 
  47.  *          LOG_STDERR -    将消息同时送到STDERR 
  48.  *返回值:成功返回log_t(>0),失败返回NULL 
  49. */  
  50. log_t *log_open( char *fname, int flags );  
  51. /* 
  52.  * 功能描述:关闭记录文件 
  53.  * 参数:      * log  - 记录文件的指针 
  54. */  
  55. void log_close( log_t *log );  
  56. #endif  

该记录服务器和线程池没有直接的关系,如果有需要,可以很方便的该记录服务器移植到自己的项目中.

lprintf函数的功能是打印记录,log指针指向了一个通过log_open函数打开的记录文件,所有的记录信息都将保存在这个文件中.通过level参数指定记录内容的分类,在log.h中定义了6种分类,分别是:DEBUG,INFO,WARN,ERROR和FATAL,便于对大量的记录信息进行分类.

[cpp]  view plain  copy
 print ?
  1. /* ------------------------------------------------------------------------- 
  2.  * log.c – 记录函数实现 
  3.   * ------------------------------------------------------------------------- 
  4.  */  
  5. #include <stdio.h>  
  6. #include <unistd.h>  
  7. #include <semaphore.h>  
  8. #include <stdarg.h>  
  9. #include <stdlib.h>  
  10. #include <string.h>  
  11. #include <errno.h>  
  12. #include <time.h>  
  13. #include <pthread.h>  
  14. #include <sys/types.h>  
  15. #include <sys/stat.h>  
  16. #include <fcntl.h>  
  17. #include "log.h"  
  18. int lprintf( log_t *log, unsigned int level, char *fmt, ... )   
  19. {  
  20.     int fd;  
  21.     int rc;  
  22.     va_list ap;  
  23.     time_t now;  
  24.     char date[50];  
  25.     static char line[LOGLINE_MAX];  
  26.     static char threadnum[10];  
  27.     int cnt;  
  28.     static char *levels[6] = { "[(bad)] ""[debug] ""[info ] ""[warn ] ",  "[error] ""[fatal] " };  
  29.     if(!log) return -1;  
  30.     if( !(log->flags&LOG_DEBUG) && level == DEBUG ) return 0;  
  31.     fd=log->fd;  
  32.     /*日期*/  
  33.     if( !(log->flags&LOG_NODATE) )   
  34.     {  
  35.         now=time(NULL);  
  36.         strcpy(date,ctime(&now));  
  37.         date[strlen(date)-6]=' ';  
  38.         date[strlen(date)-5]='\0';  
  39.     }  
  40.     /*线程号*/  
  41.     if( !(log->flags&LOG_NOTID) )   
  42.     {  
  43.         sprintf(threadnum, "(TID:%lu) ", pthread_self());  
  44.     }  
  45.     cnt = snprintf(line, sizeof(line), "%s%s%s",  
  46.                    log->flags&LOG_NODATE ? "" : date,  
  47.                    log->flags&LOG_NOLVL  ? "" :   
  48.                    (level > FATAL ? levels[0] : levels[level]),  
  49.                    log->flags&LOG_NOTID  ? "" : threadnum);  
  50.     va_start(ap, fmt);  
  51.     vsnprintf(line+cnt, sizeof(line)-cnt, fmt, ap);    /*如果输入的日志过长会自动截取*/  
  52.     va_end(ap);  
  53.     line[sizeof(line)-1] = '\0';  
  54.     if( !(log->flags&LOG_NOLF) )   
  55.     {  
  56.         /*chomp(line);*/  
  57.         /*strcpy(line+strlen(line), "\n");*/  
  58.     }  
  59.     sem_wait(&log->sem);         /*用信号实现同步*/  
  60.     rc = write(fd, line, strlen(line));  
  61.     if (log->flags&LOG_STDERR)  
  62.      write(2, line, strlen(line));  
  63.     sem_post(&log->sem);  
  64.     if( !rc ) errno = 0;  
  65.     return rc;  
  66. }  

log_open函数的作用是打开一个记录文件,其作用与fopen函数类似.

[cpp]  view plain  copy
 print ?
  1. log_t *log_open( char *fname, int flags )   
  2.    {  
  3.     log_t *log = malloc(sizeof(log_t));  
  4.     if(!log)   
  5.     {  
  6.         fprintf(stderr, "log_open: Unable to malloc()");  
  7.         goto log_open_a;  
  8.     }  
  9.     log->flags=flags;  
  10.     if( !strcmp(fname,"-") )   
  11.     {  
  12.         log->fd = 2;  
  13.     }   
  14.    else   
  15.    {  
  16.         log->fd = open(fname, O_WRONLY|O_CREAT|O_NOCTTY |   
  17.                 (flags&LOG_TRUNC ? O_TRUNC : O_APPEND) , 0666);  
  18.     }  
  19.     if( log->fd == -1 )  
  20.     {  
  21.         fprintf(stderr, "log_open: Opening logfile %s: %s", fname, strerror(errno));  
  22.         goto log_open_b;  
  23.     }  
  24.     if( sem_init(&log->sem, 0, 1) == -1 )  
  25.     {  
  26.         fprintf(stderr, "log_open: Could not initialize log semaphore.");  
  27.         goto log_open_c;  
  28.     }  
  29.     return log;  
  30. log_open_c:  
  31.     close(log->fd);  
  32. log_open_b:  
  33.     free(log);  
  34. log_open_a:  
  35.     return NULL;  
  36. }  
log_close函数的作用是关闭一个打开的记录文件.通常在函数退出的时候执行这个函数,以保证所有记录信息都正确的写入记录文件.

[cpp]  view plain  copy
 print ?
  1. void log_close( log_t *log )   
  2. {  
  3.     sem_wait(&log->sem);  
  4.     sem_destroy(&log->sem);  
  5.     close(log->fd);  
  6.     free(log);  
  7.     return;  
  8. }  

线程池的测试

[cpp]  view plain  copy
 print ?
  1. /* ------------------------------------------------------------------------- 
  2.  * testpool.c – 线程池测试程序 
  3.  * ------------------------------------------------------------------------- 
  4.  */  
  5.   
  6. #include <pthread.h>  
  7. #include "log.h"  
  8. #include "tpool.h"  
  9.   
  10. log_t *log;  /*进程全局日志文件句柄* 
  11. /*任务*/  
  12. void thread(void *arg)  
  13. {  
  14.    char * ptr=(char *)arg;  
  15.      
  16.    sleep(1);  
  17.    printf("hello world! %s\n",ptr);  
  18. }  
  19.   
  20. int main(int argc, char *argv[])  
  21. {  
  22.     tpool_t *pool;  /*线程池指针*/  
  23.      
  24.     /* 开启记录文件 */  
  25.     log=log_open("test.log", 0);  
  26.     /* 创建一个有100个工作线程,最大200个任务队列的线程池 */  
  27.     pool=tpool_init(100,200,1);  
  28.     int i;  
  29.     /* 开启记录文件 */  
  30.     * 添加100个任务*/  
  31.     for (i = 0; i<100;i++)  
  32.             tpool_add_work(pool,thread,"test!");  
  33.     sleep(10);  
  34.     /*终止线程池*/  
  35.     tpool_destroy(pool,1);   
  36.     /* 关闭记录文件 */  
  37.     log_close(log);  
  38.     pthread_exit(NULL);  
  39. }  
该例子演示了如何建立一个线程池,以及如何记录程序的运行状态,有一定的使用意义,稍加修改就可以应用到实际的项目中.能理解其中的设计思想和技巧,对自己编程能力的提高有很大的提高.
5
 
0
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值