首先,线程池是什么?顾名思义,就是把一堆开辟好的线程放在一个池子里统一管理,就是一个线程池。

  其次,为什么要用线程池,难道来一个请求给它申请一个线程,请求处理完了释放线程不行么?也行,但是如果创建线程和销毁线程的时间比线程处理请求的时间长,而且请求很多的情况下,我们的CPU资源都浪费在了创建和销毁线程上了,所以这种方法的效率比较低,于是,我们可以将若干已经创建完成的线程放在一起统一管理,如果来了一个请求,我们从线程池中取出一个线程来处理,处理完了放回池内等待下一个任务,线程池的好处是避免了繁琐的创建和结束线程的时间,有效的利用了CPU资源。

功能:节省大量线程创建销毁成本,避免线程创建过多导致程序出错。

分类:

1.启动时就创建固定数量的线程,一直处理请求------请求比较多,耗时较短。

2.启动时不创建线程,当有请求时找空闲线程,如果没有空闲线程,就创建一个工作线程,如果工作线程等待超时,则工作线程退出释放资源。-------请求一般较少,耗时较长,防止峰值压力。

线程池 = 多个线程+任务队列

用第一种方式实现一个简单的线程池:

#include<iostream>
#include<time.h>
#include<queue>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
using namespace std;

class Task
{
public:
void SetData(void* data)
{
_data = data;
}

bool Run()
{
srand(time(NULL));
int nsec = rand()%5;
cout <<"ID: " << pthread_self() << " run data:-------"
<<(char*)_data << "-------sleep " << nsec << endl;
sleep(nsec);
return true;
}
private:
void* _data;
};

class ThreadPool
{
public:
ThreadPool(int max_thread = 5, int max_queue = 10)
:_max_thread(max_thread)
,_cur_thread(max_thread)
,_stop_flag(0)
,_cap(max_queue)
{
pthread_mutex_init(&_mutex, NULL);
pthread_cond_init(&_empty,www.leyou2.net NULL);
pthread_cond_init(&_full, NULL);
}

~ThreadPool()
{
pthread_mutex_destroy(&_mutex);
pthread_cond_destroy(&_empty);
pthread_cond_destroy(&_full);
}

bool Init()
{
pthread_t tid;
for(int i = 0; i < _max_thread; ++i)
{
int ret = pthread_create(&tid, NULL, thr_start, (void*)this);
if(ret != 0)
{
cout << "pthread_create error" << endl;
return false;
}
pthread_detach(tid);
}
}
bool AddTask(Task* t)
{
pthread_mutex_lock(&_mutex);
while(Full())
{
pthread_cond_wait(&_full, &_mutex);
}

QueuePush(t);
pthread_cond_signal(&_empty);
pthread_mutex_unlock(&_mutex);
return true;
}
bool Stop()
{
pthread_mutex_lock(www.thd178.com/ &_mutex);
if(_stop_flag == 1)
{
pthread_mutex_unlock(&_mutex);
return false;
}
_stop_flag = 1;
while(_cur_thread > 0)
{
pthread_cond_broadcast(&_empty);
pthread_cond_wait(&_full, &_mutex);
}
pthread_mutex_unlock(&_mutex);
return false;
}
private:

bool Empty()
{
return _list.empty();
}

bool Full()
{
return (_cap == _list.size());
}

bool QueuePush(Task*www.michenggw.com task)
{
_list.push(task);
return true;
}

bool QueuePop(Task** task)
{
*task = _list.front();
_list.pop();
return true;
}

static void* thr_start(void *arg)
{
ThreadPool* p = (ThreadPool*)arg;

while(1)
{

pthread_mutex_lock(&p->_mutex);
//如果队列为空,且不是退出状态,陷入等待
while(p->Empty() && p->_stop_flag != 1)
pthread_cond_wait(&p->_empty, &p->_mutex);
//如果队列为空,且处于退出状态,则退出
//退出前当前线程数-1,解锁
if(p->Empty() && p->_stop_flag == 1)
{
cout << "--------thread exit" << endl;
p->_cur_thread--;
pthread_mutex_unlock(&p->_mutex);
pthread_cond_signal(www.ysyl157.com&p->_full);
pthread_exit(NULL);
}
Task *task;
p->QueuePop(&task);
pthread_mutex_unlock(&p->_mutex);

pthread_cond_signal(&p->_full);
//任务的执行,需要放在解锁外面,因为我们不知道任务需要执行多长时间
//如果先运行后解锁,有可能其他线程一直无法获取任务
task->Run();
}
return NULL;
}
private:
int _max_thread;//最大线程数量
int _cur_thread;//当前线程数量
int _stop_flag;//线程池中线程的退出标志
size_t _cap; //队列最大节点数
queue<Task*> _list;//线程池 任务队列
pthread_mutex_t _mutex;
pthread_cond_t _empty;
pthread_cond_t _full;
};

int main()
{
ThreadPool pool;
pool.Init();
Task task[10];
char* c = "hello world!!!";
for(int i = 0; i < 10; ++i)
{
sleep(1);
task[i].SetData((void*)c);
cout << "add task: " << c <<endl;
pool.AddTask(&task[i]);
}
pool.Stop();
return 0;

【Linux】线程池的更多相关文章

  1. linux线程池thrmgr源码解析

    linux线程池thrmgr源码解析 1         thrmgr线程池的作用 thrmgr线程池的作用是提高程序的并发处理能力,在多CPU的服务器上运行程序,可以并发执行多个任务. 2      ...

  2. 一个简单的linux线程池(转-wangchenxicool)

    线程池:简单地说,线程池 就是预先创建好一批线程,方便.快速地处理收到的业务.比起传统的到来一个任务,即时创建一个线程来处理,节省了线程的创建和回收的开销,响应更快,效率更高. 在linux中,使用的 ...

  3. 非常精简的Linux线程池实现(一)——使用互斥锁和条件变量

    线程池的含义跟它的名字一样,就是一个由许多线程组成的池子. 有了线程池,在程序中使用多线程变得简单.我们不用再自己去操心线程的创建.撤销.管理问题,有什么要消耗大量CPU时间的任务通通直接扔到线程池里 ...

  4. Linux线程池的实现

    线程池的实现 1:自定义封装的条件变量 //condition.h #ifndef _CONDITION_H_ #define _CONDITION_H_ #include <pthread.h ...

  5. linux线程池

    typedef struct task_node { void *arg; /* fun arg. */ void *(*fun) (void *); /* the real work of the ...

  6. Linux线程池在server上简单应用

    一.问题描写叙述 如今以C/S架构为例.client向server端发送要查找的数字,server端启动线程中的线程进行对应的查询.将查询结果显示出来. 二.实现方案 1. 整个project以cli ...

  7. Linux下简易线程池

    线程池简介 线程池是可以用来在后台执行多个任务的线程集合. 这使主线程可以自由地异步执行其他任务.线程池通常用于服务器应用程序. 每个传入请求都将分配给线程池中的一个线程,因此可以异步处理请求,而不会 ...

  8. 线程池(Linux实现)

    讨论QQ群:135202158 本文技术参考了sourceforge项目c thread pool,链接:http://sourceforge.net/projects/cthpool/ 线程池如上一 ...

  9. Linux平台下线程池的原理及实现

    转自:http://blog.csdn.net/lmh12506/article/details/7753952 前段时间在github上开了个库,准备实现自己的线程池的,因为换工作的事,一直也没有实 ...

  10. 高效线程池之无锁化实现(Linux C)

    from:http://blog.csdn.net/xhjcehust/article/details/45844901 笔者之前练手写过一个小的线程池版本(已上传至https://github.co ...

随机推荐

  1. 我所用过的nginx的功能

    前言 当我们提起集群时,一般所用的插件就是nginx.nginx功能如今越来越完善.第三方模块也多如牛毛,在此,总结一下不牵扯第三方模块所具有的功能. 基本功能 反向代理 负载均衡 HTTP服务器(动 ...

  2. 吐血分享:QQ群霸屏技术教程2017(活跃篇)

    热门词的群排名,在前期优化准备充分的情况下,活跃度不失为必杀技. 在<吐血分享:QQ群霸屏技术(初级篇)>中,我们提及到热门词的群排名,有了前面的基础,我们就可以进入深度优化,实现绝对的霸 ...

  3. BGP(边界网关协议)简述

    BGP的起源 不同自治系统(路由域)间路由交换与管理的需求推动了EGP的发展,但是EGP的算法简单,无法选路,从而被BGP取代. 自治系统:(AS) IGP:自治系统内部协议,ospf,rip,is- ...

  4. (数据科学学习手札24)逻辑回归分类器原理详解&Python与R实现

    一.简介 逻辑回归(Logistic Regression),与它的名字恰恰相反,它是一个分类器而非回归方法,在一些文献里它也被称为logit回归.最大熵分类器(MaxEnt).对数线性分类器等:我们 ...

  5. java stream 处理分组后取每组最大

    有一个需求功能:先按照某一字段分组,再按照另外字段获取最大的那个 Map<String, HitRuleConfig> configMap = configList.parallelStr ...

  6. 20145202马超《JAVA》预备作业3

    虚拟机的安装[http://www.cnblogs.com/tuolemi/p/5861062.html] Linux命令[http://www.cnblogs.com/tuolemi/p/58781 ...

  7. 【Consul】关于健康检查的一点思考

    健康检查是Consul提供的一项主要功能,其配置格式如下: { "check": { "id": "redis", "name&q ...

  8. React+DvaJS 之 hook 路由权限控制

    博客 学院 下载 GitChat TinyMind 论坛 APP 问答 商城 VIP 活动 招聘 ITeye 写博客 发Chat 登录注册 原 React+DvaJS 之 hook 路由权限控制 20 ...

  9. itop-4412开发板使用第一篇-信号量的学习使用

    1. 本次基于itop-4412研究下Linux信号量的使用方法. 2. 创建信号量的函数,信号量的头文件在那个路径?编译应用程序的话,头文件有3个路径,内核源码头文件,交叉编译器头文件,ubuntu ...

  10. goroutine 并发之搜索文件内容

    golang并发编程 - 例子解析 February 26, 2013 最近在看<Programming in Go>, 其中关于并发编程写得很不错, 受益非浅, 其中有一些例子是需要多思 ...