C语言实现的简单的线程池

http://www.linuxidc.com/Linux/2013-01/77619.htm

有时我们会需要大量线程来处理一些相互独立的任务,为了避免频繁的申请释放线程所带来的开销,我们可以使用线程池。下面是一个C语言实现的简单的线程池。

头文件:

   1: #ifndef THREAD_POOL_H__
   2: #define THREAD_POOL_H__
   3:  
   4: #include <pthread.h>
   5:  
   6: /* 要执行的任务链表 */
   7: typedef struct tpool_work {
   8:     void*               (*routine)(void*);       /* 任务函数 */
   9:     void                *arg;                    /* 传入任务函数的参数 */
  10:     struct tpool_work   *next;                    
  11: }tpool_work_t;
  12:  
  13: typedef struct tpool {
  14:     int             shutdown;                    /* 线程池是否销毁 */
  15:     int             max_thr_num;                /* 最大线程数 */
  16:     pthread_t       *thr_id;                    /* 线程ID数组 */
  17:     tpool_work_t    *queue_head;                /* 线程链表 */
  18:     pthread_mutex_t queue_lock;                    
  19:     pthread_cond_t  queue_ready;    
  20: }tpool_t;
  21:  
  22: /*
  23:  * @brief     创建线程池 
  24:  * @param     max_thr_num 最大线程数
  25:  * @return     0: 成功 其他: 失败  
  26:  */
  27: int
  28: tpool_create(int max_thr_num);
  29:  
  30: /*
  31:  * @brief     销毁线程池 
  32:  */
  33: void
  34: tpool_destroy();
  35:  
  36: /*
  37:  * @brief     向线程池中添加任务
  38:  * @param    routine 任务函数指针
  39:  * @param     arg 任务函数参数
  40:  * @return     0: 成功 其他:失败 
  41:  */
  42: int
  43: tpool_add_work(void*(*routine)(void*), void *arg);
  44:  
  45: #endif

实现:

   1: #include <unistd.h>
   2: #include <stdlib.h>
   3: #include <errno.h>
   4: #include <string.h>
   5: #include <stdio.h>
   6:  
   7: #include "tpool.h"
   8:  
   9: static tpool_t *tpool = NULL;
  10:  
  11: /* 工作者线程函数, 从任务链表中取出任务并执行 */
  12: static void* 
  13: thread_routine(void *arg)
  14: {
  15:     tpool_work_t *work;
  16:     
  17:     while(1) {
  18:         /* 如果线程池没有被销毁且没有任务要执行,则等待 */
  19:         pthread_mutex_lock(&tpool->queue_lock);
  20:         while(!tpool->queue_head && !tpool->shutdown) {
  21:             pthread_cond_wait(&tpool->queue_ready, &tpool->queue_lock);
  22:         }
  23:         if (tpool->shutdown) {
  24:             pthread_mutex_unlock(&tpool->queue_lock);
  25:             pthread_exit(NULL);
  26:         }
  27:         work = tpool->queue_head;
  28:         tpool->queue_head = tpool->queue_head->next;
  29:         pthread_mutex_unlock(&tpool->queue_lock);
  30:  
  31:         work->routine(work->arg);
  32:         free(work);
  33:     }
  34:     
  35:     return NULL;   
  36: }
  37:  
  38: /*
  39:  * 创建线程池 
  40:  */
  41: int
  42: tpool_create(int max_thr_num)
  43: {
  44:     int i;
  45:  
  46:     tpool = calloc(1, sizeof(tpool_t));
  47:     if (!tpool) {
  48:         printf("%s: calloc failed\n", __FUNCTION__);
  49:         exit(1);
  50:     }
  51:     
  52:     /* 初始化 */
  53:     tpool->max_thr_num = max_thr_num;
  54:     tpool->shutdown = 0;
  55:     tpool->queue_head = NULL;
  56:     if (pthread_mutex_init(&tpool->queue_lock, NULL) !=0) {
  57:         printf("%s: pthread_mutex_init failed, errno:%d, error:%s\n",
  58:             __FUNCTION__, errno, strerror(errno));
  59:         exit(1);
  60:     }
  61:     if (pthread_cond_init(&tpool->queue_ready, NULL) !=0 ) {
  62:         printf("%s: pthread_cond_init failed, errno:%d, error:%s\n", 
  63:             __FUNCTION__, errno, strerror(errno));
  64:         exit(1);
  65:     }
  66:     
  67:     /* 创建工作者线程 */
  68:     tpool->thr_id = calloc(max_thr_num, sizeof(pthread_t));
  69:     if (!tpool->thr_id) {
  70:         printf("%s: calloc failed\n", __FUNCTION__);
  71:         exit(1);
  72:     }
  73:     for (i = 0; i < max_thr_num; ++i) {
  74:         if (pthread_create(&tpool->thr_id[i], NULL, thread_routine, NULL) != 0){
  75:             printf("%s:pthread_create failed, errno:%d, error:%s\n", __FUNCTION__, 
  76:                 errno, strerror(errno));
  77:             exit(1);
  78:         }
  79:         
  80:     }    
  81:  
  82:     return 0;
  83: }
  84:  
  85: /* 销毁线程池 */
  86: void
  87: tpool_destroy()
  88: {
  89:     int i;
  90:     tpool_work_t *member;
  91:  
  92:     if (tpool->shutdown) {
  93:         return;
  94:     }
  95:     tpool->shutdown = 1;
  96:  
  97:     /* 通知所有正在等待的线程 */
  98:     pthread_mutex_lock(&tpool->queue_lock);
  99:     pthread_cond_broadcast(&tpool->queue_ready);
 100:     pthread_mutex_unlock(&tpool->queue_lock);
 101:     for (i = 0; i < tpool->max_thr_num; ++i) {
 102:         pthread_join(tpool->thr_id[i], NULL);
 103:     }
 104:     free(tpool->thr_id);
 105:  
 106:     while(tpool->queue_head) {
 107:         member = tpool->queue_head;
 108:         tpool->queue_head = tpool->queue_head->next;
 109:         free(member);
 110:     }
 111:  
 112:     pthread_mutex_destroy(&tpool->queue_lock);    
 113:     pthread_cond_destroy(&tpool->queue_ready);
 114:  
 115:     free(tpool);    
 116: }
 117:  
 118: /* 向线程池添加任务 */
 119: int
 120: tpool_add_work(void*(*routine)(void*), void *arg)
 121: {
 122:     tpool_work_t *work, *member;
 123:     
 124:     if (!routine){
 125:         printf("%s:Invalid argument\n", __FUNCTION__);
 126:         return -1;
 127:     }
 128:     
 129:     work = malloc(sizeof(tpool_work_t));
 130:     if (!work) {
 131:         printf("%s:malloc failed\n", __FUNCTION__);
 132:         return -1;
 133:     }
 134:     work->routine = routine;
 135:     work->arg = arg;
 136:     work->next = NULL;
 137:  
 138:     pthread_mutex_lock(&tpool->queue_lock);    
 139:     member = tpool->queue_head;
 140:     if (!member) {
 141:         tpool->queue_head = work;
 142:     } else {
 143:         while(member->next) {
 144:             member = member->next;
 145:         }
 146:         member->next = work;
 147:     }
 148:     /* 通知工作者线程,有新任务添加 */
 149:     pthread_cond_signal(&tpool->queue_ready);
 150:     pthread_mutex_unlock(&tpool->queue_lock);
 151:  
 152:     return 0;    
 153: }
 154:     
 155:  

测试代码:

   1: #include <unistd.h>
   2: #include <stdio.h>
   3: #include <stdlib.h>
   4: #include "tpool.h"
   5:  
   6: void *func(void *arg)
   7: {
   8:     printf("thread %d\n", (int)arg);
   9:     return NULL;
  10: }
  11:  
  12: int
  13: main(int arg, char **argv)
  14: {
  15:     if (tpool_create(5) != 0) {
  16:         printf("tpool_create failed\n");
  17:         exit(1);
  18:     }
  19:     
  20:     int i;
  21:     for (i = 0; i < 10; ++i) {
  22:         tpool_add_work(func, (void*)i);
  23:     }
  24:     sleep(2);
  25:     tpool_destroy();
  26:     return 0;
  27: }

这个实现是在调用tpool_destroy之后,仅将当前正在执行的任务完成之后就会退出,我们也可以修改代码使得线程池在执行完任务链表中所有任务后再退出。


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/383833.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C++获取当前时间

可以使用windowsAPI直接获取。 例如&#xff1a; #include<windows.h> #include<cstdio>using namespace std;int main() {SYSTEMTIME now;GetLocalTime(&now);printf("现在是%02d时%02d分%02d秒\n",now.wHour,now.wMinute,now.wSecond);printf(&…

成员函数后面加上const的作用

const表示成员函数不会修改类中的数据成员。 规则&#xff1a; 在类中被const 声明的函数只能访问const 函数&#xff0c;而非const 函数可以访问任意成员函数。在成员函数中不管数据是否具有const 属性&#xff0c;编译器检查的的是是否有修改&#xff08;赋值&#xff0c;自…

简单Linux C线程池

http://www.cnblogs.com/venow/archive/2012/11/22/2779667.html 大多数的网络服务器&#xff0c;包括Web服务器都具有一个特点&#xff0c;就是单位时间内必须处理数目巨大的连接请求&#xff0c;但是处理时间却是比较短的。在传统的多线程服务器模型中是这样实现的&#xff1…

C++创建对象:栈和堆的区别

首先我们应该了解栈和堆的差别&#xff1a; 详细信息&#xff1a;传送门 栈相当于函数自带的存储空间&#xff0c;在windows下一般为2M,在Linux下一般为8M&#xff0c;存取速度稍微快一点。堆是系统的空间&#xff0c;相对较大&#xff0c;一般为2G&#xff0c;效率稍微慢一点…

IO多路复用之poll总结

http://www.cnblogs.com/Anker/p/3261006.html 1、基本知识 poll的机制与select类似&#xff0c;与select在本质上没有多大差别&#xff0c;管理多个描述符也是进行轮询&#xff0c;根据描述符的状态进行处理&#xff0c;但是poll没有最大文件描述符数量的限制。poll和select同…

【C++学习笔记二】C++继承

继承 继承允许我们一句另一个类来定义一个类&#xff0c;这使得继承和维护一个程序变得更加容易&#xff0c;也达到了重用代码功能和提高执行效率的效果。 一般格式为&#xff1a; class 派生类名 :访问修饰符 基类名{};其中访问修饰符是public protected private中的一个&a…

处理大并发之二 对epoll的理解,epoll客户端服务端代码

http://blog.csdn.net/wzjking0929/article/details/51838370 序言&#xff1a; 该博客是一系列的博客&#xff0c;首先从最基础的epoll说起&#xff0c;然后研究libevent源码及使用方法&#xff0c;最后研究nginx和node.js&#xff0c;关于select,poll这里不做说明&#xff0c…

C++基类指针指向派生类(指针)

我们常用基类指针指向派生类对象来实现多态性。 私有继承不允许基类指针指向派生类 基类指针只能访问到基类中含有的公有成员。 当用基类指针指向派生类对象在动态分配堆上内存的时候&#xff0c;析构函数必须是虚函数! 成员如果是数据成员的话访问的是基类的版本&#xff…

C++虚继承中构造函数和析构函数顺序问题以及原理

多重继承的问题&#xff1a;多个类B,C,…继承同一个类A导致如果X继承了B,C,…那么在X中将还有多个A中成员的拷贝&#xff0c;如果想要访问A中的成员如果不加名字空间将会导致二义性&#xff0c;这种拷贝大多是没有实际意义的&#xff0c;为了避免这种空间浪费&#xff0c;C有虚…

一个简单的linux线程池

http://blog.csdn.net/wzjking0929/article/details/20312675 线程池&#xff1a;简单地说&#xff0c;线程池 就是预先创建好一批线程&#xff0c;方便、快速地处理收到的业务。比起传统的到来一个任务&#xff0c;即时创建一个线程来处理&#xff0c;节省了线程的创建和回收的…

【C++学习笔记三】C++多态、抽象(接口)

当类之间存在多种层次结构&#xff0c;并且类之间通过继承关联时就会用到多态。 虚函数在子类中的覆盖版本和该函数在基类中的原始版本必须有相同的函数签名、函数名、形参名、常属性。如果返回值为非类类型&#xff0c;则必须相同&#xff0c;如果是类类型A的指针或者引用&am…

C++重载和重写的条件以及重写后对基类函数的覆盖

重载&#xff1a;同一个类中名字相同&#xff0c;参数列表不同的方法构成重载函数&#xff0c;和返回值没有关系。这就意味着就算返回值不同&#xff0c;只要名字相同参数列表相同编译器还是会报错&#xff0c;觉得一函数被定义了两次。 重写&#xff1a;派生类中只要函数名字…

C++静态成员和静态方法

在类中&#xff0c;静态成员可以实现多个对象之间共享数据&#xff0c;同时保证了安全性。静态数据对该类的所有对象是公有的&#xff0c;存储一处供所有对象使用。 注意&#xff1a; 静态成员定义时需要在前面加上关键字static静态成员必须初始化且必须在类外进行&#xff0…

基于epoll的简单的http服务器

http://blog.csdn.net/fangjian1204/article/details/34415651 http服务器已经可以处理并发连接&#xff0c;支持多个客户端并发访问&#xff0c;每个连接可以持续读写数据&#xff0c;当然&#xff0c;这只是一个简单的学习例子&#xff0c;还有很多bug&#xff0c;发表出来只…

C++单例模式简单实现

有时候我们需要某个类只能被实例化一次&#xff0c;并且其他类都可以访问到这个类&#xff0c;就需要这种设计模式。 例如我们想要做个资源管理器&#xff0c;显然这个管理器只能有一个。 这种模式有很多实现方式&#xff0c;这里介绍最简单的一种&#xff0c;想要了解更多可…

Linux C++ 实现线程池

http://blog.csdn.net/qq_25425023/article/details/53914609 线程池中的线程&#xff0c;在任务队列为空的时候&#xff0c;等待任务的到来&#xff0c;任务队列中有任务时&#xff0c;则依次获取任务来执行&#xff0c;任务队列需要同步。 Linux线程同步有多种方法&#xff…

C++制表符

制表符的转义字符为\t&#xff0c;一般情况下长度为8个空格&#xff0c;这里的8个指的是从上一个字符串的开头开始算&#xff0c;往后数8个&#xff0c;不够的话就补空格。 如果前面的字符串的长度大于等于8个&#xff0c;例如前面字符串的长度为x,那么就会补(8-x%8)个空格 例…

C++派生类含有成员对象构造函数析构函数顺序

参考博客&#xff1a;传送门1 当类中含有对象成员时&#xff1a; 类的构造函数要包含对成员对象的初始化&#xff0c;如果构造函数的成员初始化列表没有包含对成员对象的初始化&#xff0c;系统会自动调用成员对象的无参构造函数。顺序上&#xff1a;先调用成员对象的构造函数…

c,c++中字符串处理函数strtok,strstr,strchr,strsub

http://blog.csdn.net/wangqing_12345/article/details/51760220 1&#xff0c;字符串切割函数 函数原型&#xff1a;char *strtok(char *s, char *delim); 函数功能&#xff1a;把字符串s按照字符串delim进行分割&#xff0c;然后返回分割的结果。 函数使用说&#xff1a; 1…

C++虚基类成员可见性

详见《CPrimer》[第五版]719页 如果继承路径上没有和虚基类成员重名的成员&#xff0c;则不存在二义性&#xff0c;因为我们仅能访问到虚基类成员。 当访问仅有一条继承路径上含有和虚基类成员重名的成员&#xff0c;也不存在二义性。派生类的成员的优先级比基类的成员高&…