Linux下简单的多线程编程--线程池的实现
/* 写在前面的话:
今天刚“开原”,选择了一篇关于线程池的文件与大家分享,希望能对您学习有所帮助,也希望能与大家共同学习!
选择在这个特殊的时候注册并发文章也是有一些我个人特殊的意义的,看我的id(西游小学生.45)就知道了,哈哈。在这里也很感谢博客园的员工,刚发申请两分钟就同意了。
*/
最近由于要写一个类似于QQ的程序,所以想到要用到多线程。既然要用多线程,那何不写一个线程池?于是上网搜了搜多线程的代码,发现大多都不是很完善,或者有些小bug。所以,在这里贴出一个完整的,经过我多重测试的,先贴上一个线程池的简单实现过程(固定大小的线程池),稍后和网络编程的结合过些天会再贴出来。这里引用Linux的一句话:“
talk is cheap show me the code
”。所以我的博客大部分都会给大家贴代码的,谢谢。
首先,不得不提的就是线程池的好处:
简单来说,如果调用一个线程分为:
t1创建线程
t2完成作业
t3销毁线程
那么如果我们有100个作业要完成,总时间T=100*(t1+t2+t3)。但如果我们提前申请一个10个线程的固定大小线程池,那么完成作业的总时间为申请10个线程和销毁10个线程以及100个作业的时间,及T=10*t1+100*t2+10*t3。所以,线程池最大的优势就是节省了线程申请以及销毁的时间!
下面是具体的代码实现:
void* (*routine)(int); 任务函数,该任务的处理函数
int arg; 传入任务函数的参数
struct tpool_work *next; 任务队列的下一个节点
}tpool_work_t;
typedef struct tpool { 线程池
int shutdown; 线程池是否销毁
int max_thr_num; 最大线程数
pthread_t *thr_id; 线程ID数组
tpool_work_t *queue_head; 任务队列的头结点
pthread_mutex_t queue_lock; 互斥锁
pthread_cond_t queue_ready; 条件变量
}tpool_t;
/*************************************************************************
> File Name: tpool.h
> Author:
> Mail:
> Created Time: 2015年04月01日 星期三 17时34分00秒
************************************************************************/
#ifndef THREAD_POOL_H__
#define THREAD_POOL_H__
#include <pthread.h>
/* 要执行的任务链表 */
typedef struct tpool_work {
void* (*routine)(int); /* 任务函数 */
int arg; /* 传入任务函数的参数 */
struct tpool_work *next;
}tpool_work_t;
typedef struct tpool {
int shutdown; /* 线程池是否销毁 */
int max_thr_num; /* 最大线程数 */
pthread_t *thr_id; /* 线程ID数组 */
tpool_work_t *queue_head; /* 线程链表 */
pthread_mutex_t queue_lock;
pthread_cond_t queue_ready;
}tpool_t;
/*
* @brief 创建线程池
* @param max_thr_num 最大线程数
* @return 0: 成功 其他: 失败
*/
int
tpool_create(int max_thr_num);
/*
* @brief 销毁线程池
*/
void
tpool_destroy();
/*
* @brief 向线程池中添加任务
* @param routine 任务函数指针
* @param arg 任务函数参数
* @return 0: 成功 其他:失败
*/
int
tpool_add_work(void*(*routine)(int), int arg);
#endif
/*************************************************************************
> File Name: func.c
> Author:
> Mail:
> Created Time: 2015年04月01日 星期三 17时35分56秒
************************************************************************/
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include "tpool.h"
static tpool_t *tpool = NULL;
void
print_work(tpool_work_t *head) //输出任务列队当前工作
{
tpool_work_t *work= head;
printf("\n当前任务列队里还有的任务是:(任务的参数是)\n");
while(work){
printf("%d ",work->arg);
work = work->next;
}
printf("\n");
}
/* 工作者线程函数, 从任务链表中取出任务并执行 */
static void*
thread_routine(void *arg)
{
tpool_work_t *work; //任务链表
while(1) {
/* 如果线程池没有被销毁且没有任务要执行,则等待 */
pthread_mutex_lock(&tpool->queue_lock); //锁住线程池
while(!tpool->queue_head && !tpool->shutdown) {
pthread_cond_wait(&tpool->queue_ready, &tpool->queue_lock);
}
if (tpool->shutdown) { //0没有注销
pthread_mutex_unlock(&tpool->queue_lock);
pthread_exit(NULL);
}
sleep(3);
// print_work(tpool->queue_head);
//取出任务链表头的一个工作
work = tpool->queue_head;
tpool->queue_head = tpool->queue_head->next;
pthread_mutex_unlock(&tpool->queue_lock);
work->routine(work->arg);
free(work);
}
return NULL;
}
/*
* 创建线程池
*/
int
tpool_create(int max_thr_num)
{
int i;
tpool = calloc(1, sizeof(tpool_t)); //线程池tpool
if (!tpool) {
printf("%s: calloc failed\n", __FUNCTION__);
exit(1);
}
/* 初始化 */
tpool->max_thr_num = max_thr_num; //初始化最大线程池数
tpool->shutdown = 0; //线程池注销设为0未注
tpool->queue_head = NULL; //线程池链表
if (pthread_mutex_init(&tpool->queue_lock, NULL) !=0) { //初始化线程锁
printf("%s: pthread_mutex_init failed, errno:%d, error:%s\n",
__FUNCTION__, errno, strerror(errno));
exit(1);
}
if (pthread_cond_init(&tpool->queue_ready, NULL) !=0 ) { //初始化条件变量
printf("%s: pthread_cond_init failed, errno:%d, error:%s\n",
__FUNCTION__, errno, strerror(errno));
exit(1);
}
/* 创建工作者线程 */
tpool->thr_id = calloc(max_thr_num, sizeof(pthread_t));//申请线程ID数组
if (!tpool->thr_id) {
printf("%s: calloc failed\n", __FUNCTION__);
exit(1);
}
for (i = 0; i < max_thr_num; ++i) {
if (pthread_create(&tpool->thr_id[i], NULL, thread_routine, NULL) != 0){
printf("%s:pthread_create failed, errno:%d, error:%s\n", __FUNCTION__,
errno, strerror(errno));
exit(1);
}
}
return 0;
}
/* 销毁线程池 */
void
tpool_destroy()
{
int i;
tpool_work_t *member;
if (tpool->shutdown) {
return;
}
tpool->shutdown = 1;
/* 通知所有正在等待的线程 */
pthread_mutex_lock(&tpool->queue_lock);
pthread_cond_broadcast(&tpool->queue_ready);
pthread_mutex_unlock(&tpool->queue_lock);
for (i = 0; i < tpool->max_thr_num; ++i) {
pthread_join(tpool->thr_id[i], NULL);
}
free(tpool->thr_id);
while(tpool->queue_head) {
member = tpool->queue_head;
tpool->queue_head = tpool->queue_head->next;
free(member);
}
pthread_mutex_destroy(&tpool->queue_lock);
pthread_cond_destroy(&tpool->queue_ready);
free(tpool);
}
/* 向线程池添加任务 */
int
tpool_add_work(void*(*routine)(int), int arg)
{
tpool_work_t *work, *member;
if (!routine){
printf("%s:Invalid argument\n", __FUNCTION__);
return -1;
}
work = malloc(sizeof(tpool_work_t)); //申请一个任务结点
if (!work) { //申请失败
printf("%s:malloc failed\n", __FUNCTION__);
return -1;
}
work->routine = routine; //线程执行函数设为main中传进来的参数
work->arg = arg; //线程执行函数的参数设置为main中传进来的参数
work->next = NULL;
pthread_mutex_lock(&tpool->queue_lock); //锁住线程池锁
member = tpool->queue_head;
if (!member) { //找到线程链表中最后一个结点,并该工作放置于线程链表尾
tpool->queue_head = work;
} else {
while(member->next) {
member = member->next;
}
member->next = work;
}
/* 通知工作者线程,有新任务添加 */
pthread_cond_signal(&tpool->queue_ready);
pthread_mutex_unlock(&tpool->queue_lock);
return 0;
}
void *func(int arg)
{
printf("thread %d threadID is: %d\n",arg,(int)pthread_self());
print_work(tpool->queue_head);
sleep(3);
return NULL;
}
int
main(int arg, char **argv)
{
if (tpool_create(5) != 0) {
printf("tpool_create failed\n");
exit(1);
}
int i;
for (i = 0; i < 10; ++i) {
tpool_add_work(func, i);
// usleep(1);
}
sleep(10); //如果sleep无或时间太短,注意主线程可能先于其他线程完成导致部分作业未完成
tpool_destroy();
return 0;
}
Linux下简单的多线程编程--线程池的实现的更多相关文章
- linux下C语言多线程编程实例
用一个实例.来学习linux下C语言多线程编程实例. 代码目的:通过创建两个线程来实现对一个数的递加.代码: //包含的头文件 #include <pthread.h> #include ...
- linux下C++的多线程编程
1. 引言 线程(thread)技术早在60年代就被提出,但真正应用多线程到操作系统中去,是在80年代中期,solaris是这方面的佼佼者.传统的Unix也支持线程的概念,但是在一个进程(proces ...
- Linux程序设计学习笔记----多线程编程线程同步机制之相互排斥量(锁)与读写锁
相互排斥锁通信机制 基本原理 相互排斥锁以排他方式防止共享数据被并发訪问,相互排斥锁是一个二元变量,状态为开(0)和关(1),将某个共享资源与某个相互排斥锁逻辑上绑定之后,对该资源的訪问操作例如以下: ...
- Java多线程与线程池技术
一.序言 Java多线程编程线程池被广泛使用,甚至成为了标配. 线程池本质是池化技术的应用,和连接池类似,创建连接与关闭连接属于耗时操作,创建线程与销毁线程也属于重操作,为了提高效率,先提前创建好一批 ...
- Linux下的C Socket编程 -- server端的简单示例
Linux下的C Socket编程(三) server端的简单示例 经过前面的client端的学习,我们已经知道了如何创建socket,所以接下来就是去绑定他到具体的一个端口上面去. 绑定socket ...
- Linux下的C Socket编程 -- server端的继续研究
Linux下的C Socket编程(四) 延长server的生命周期 在前面的一个个例子中,server在处理完一个连接后便会立即结束掉自己,然而这种server并不科学啊,server应该是能够一直 ...
- C#多线程之线程池篇3
在上一篇C#多线程之线程池篇2中,我们主要学习了线程池和并行度以及如何实现取消选项的相关知识.在这一篇中,我们主要学习如何使用等待句柄和超时.使用计时器和使用BackgroundWorker组件的相关 ...
- CreateThread简单那多线程编程
CreateThread简单那多线程编程 作者:vpoet mail:vpoet_sir@163.com 在进行多任务处理的时候我们往往会用到多线程技术,多线程理论上是多个线程同事处理不同的工作,但是 ...
- Qt中的多线程与线程池浅析+实例
1. Qt中的多线程与线程池 今天学习了Qt中的多线程和线程池,特写这篇博客来记录一下 2. 多线程 2.1 线程类 QThread Qt 中提供了一个线程类,通过这个类就可以创建子线程了,Qt 中一 ...
随机推荐
- MVC项目中怎样用JS导出EasyUI DataGrid为Excel
在做一中考评项目的时候,遇到了这么一个需求.就是把评教后得到的老师的成绩导出为Excel.事实上需求非常普通.实现起来有些复杂.由于老师考评不但有固定的考核项,还有额外加分项.于是我们就抽出来了一个表 ...
- JavaScript-2.4 改进的Hello程序,使用div,---ShinePans
<html> <head> <meta http-equiv="content-type" content="text/html;chars ...
- nodejs 命令行交互
人机交互 function readSyncByfs(tips) { tips = tips || '> '; process.stdout.write(tips); process.stdin ...
- 通过WSDL命令,将WSDL生成代理类
VS2010 打开命令行窗口(开始-VS2010--Visual Studio Tools--Visual Studio Command Prompt) 输入: wsdl /l:cs /n:newN ...
- Atitit.attilax的 case list 项目经验 案例列表
Atitit.attilax的 case list 项目经验 案例列表 1. Atian inputmethod 输入法3 2. Ati desktop engine桌面引擎3 3. Acc资金账户系 ...
- 分享我们必须知道的高速GTX技术
eSATA接口只有几根线为什么那么快?连上网线显示的1Gbps是不是很令人兴奋!没错他们都用了高速GTX技术,GTX全称为Gigabit Transceiver,是为了满足现代数字处理技术和计算技术庞 ...
- Windows 8 64bit Xilinx ISE(14.7) Fix License
http://www.youtube.com/watch?v=ttPbEcNjdo8 It can work successfully!
- Pycharm快捷键小结
1.编辑(Editing) Ctrl + Space 基本的代码完成(类.方法.属性)Ctrl + Alt + Space 快速导入任意类Ctrl + Shift + Enter 语句完成Ctrl + ...
- Google Pagespeed,自动压缩优化JS/CSS/Image
Google Pagespeed,自动压缩优化JS/CSS/Image 浏览: 发布日期:// 分类:技术分享 关键字: Nginx Appache Pagespeed 自动压缩优化JS/CSS/Im ...
- HugePage简介和KVM中使用HugePage
现在,有许多的处理器架构都支持多种的内存页大小,其中就包括比一般的page size大很多的huge page.就目前来说,尽管在个人电脑中基本都实现了对huge page的支持,然而,huge pa ...