python线程池的实现
由于系统初始架构的问题,一直采用单线程运行,而当我在导入大批量数据时,要去请求大量的外部数据,使得IO一直爆满,第一反应就是使用纯种池来解决。
在网上查了一下资料,发现已经有人写了相关的应用了:
http://blog.daviesliu.net/2006/10/09/234822/
后来还发现国外一个比较完善的开源的项目:
http://chrisarndt.de/en/software/python/threadpool/
写了一段测试代码,目的是去抓一批页面过来,这些操作都被分布到50个线程当中,当然,我这种测试方法不是很准,说成是一个使用例子更合适一些,而且,如果是在IO密集型的应用中,完全可以多开几个线程:
- import urllib2
- import time
- import socket
- from datetime import datetime
- from thread_pool import *
- def main():
- url_list = {"sina":"http://www.sina.com.cn",
- "sohu":"http://www.sohu.com",
- "yahoo":"http://www.yahoo.com",
- "xiaonei":"http://www.xiaonei.com",
- "qihoo":"http://www.qihoo.com",
- "laohan":"http://www.laohan.org",
- "eyou":"http://www.eyou.com",
- "chinaren":"http://www.chinaren.com",
- "douban":"http://www.douban.com",
- "163":"http://www.163.com",
- "daqi":"http://www.daqi.com",
- "qq":"http://www.qq.com",
- "baidu_1":"http://www.baidu.com/s?wd=asdfasdf",
- "baidu_2":"http://www.baidu.com/s?wd=dddddddf",
- "google_1":"http://www.baidu.com/s?wd=sadfas",
- "google_2":"http://www.baidu.com/s?wd=sadflasd",
- "hainei":"http://www.hainei.com",
- "microsoft":"http://www.microsoft.com",
- "wlzuojia":"http://www.wlzuojia.com"}
- #使用线程池
- socket.setdefaulttimeout(10)
- print 'start testing'
- wm = WorkerManager(50)
- for url_name in url_list.keys():
- wm.add_job(do_get_con, url_name, url_list[url_name])
- wm.wait_for_complete()
- print 'end testing'
- def do_get_con(url_name,url_link):
- try:
- fd = urllib2.urlopen(url_link)
- data = fd.read()
- f_hand = open("/tmp/ttt/%s" % url_name,"w")
- f_hand.write(data)
- f_hand.close()
- except Exception,e:
- pass
- if __name__ == "__main__":
- main()
thread_pool的代码(非原创,转自:http://blog.daviesliu.net/2006/10/09/234822/)
- import Queue, threading, sys
- from threading import Thread
- import time
- import urllib
- # working thread
- class Worker(Thread):
- worker_count = 0
- timeout = 1
- def __init__( self, workQueue, resultQueue, **kwds):
- Thread.__init__( self, **kwds )
- self.id = Worker.worker_count
- Worker.worker_count += 1
- self.setDaemon( True )
- self.workQueue = workQueue
- self.resultQueue = resultQueue
- self.start( )
- def run( self ):
- ''' the get-some-work, do-some-work main loop of worker threads '''
- while True:
- try:
- callable, args, kwds = self.workQueue.get(timeout=Worker.timeout)
- res = callable(*args, **kwds)
- print "worker[%2d]: %s" % (self.id, str(res) )
- self.resultQueue.put( res )
- #time.sleep(Worker.sleep)
- except Queue.Empty:
- break
- except :
- print 'worker[%2d]' % self.id, sys.exc_info()[:2]
- raise
- class WorkerManager:
- def __init__( self, num_of_workers=10, timeout = 2):
- self.workQueue = Queue.Queue()
- self.resultQueue = Queue.Queue()
- self.workers = []
- self.timeout = timeout
- self._recruitThreads( num_of_workers )
- def _recruitThreads( self, num_of_workers ):
- for i in range( num_of_workers ):
- worker = Worker( self.workQueue, self.resultQueue )
- self.workers.append(worker)
- def wait_for_complete( self):
- # ...then, wait for each of them to terminate:
- while len(self.workers):
- worker = self.workers.pop()
- worker.join( )
- if worker.isAlive() and not self.workQueue.empty():
- self.workers.append( worker )
- print "All jobs are are completed."
- def add_job( self, callable, *args, **kwds ):
- self.workQueue.put( (callable, args, kwds) )
- def get_result( self, *args, **kwds ):
- return self.resultQueue.get( *args, **kwds )
引自: http://www.handaoliang.com/article_38.html
python线程池的实现相关推荐
- Python 线程池 ThreadPoolExecutor(二) - Python零基础入门教程
目录 一.Python 线程池前言 二.Python 线程池 ThreadPoolExecutor 常用函数 1.线程池 as_completed 函数使用 2.线程池 map 函数使用 3.线程池 ...
- Python 线程池 ThreadPoolExecutor(一) - Python零基础入门教程
目录 一.Python 线程池前言 二.Python 线程池原理 三.Python 线程池 ThreadPoolExecutor 函数介绍 四.Python 线程池 ThreadPoolExecuto ...
- python线程池原理及使用
python线程池及其原理和使用 系统启动一个新线程的成本是比较高的,因为它涉及与操作系统的交互.在这种情形下,使用线程池可以很好地提升性能,尤其是当程序中需要创建大量生存期很短暂的线程时,更应该考虑 ...
- python 线程池 concurrent.futures ThreadPoolExecutor
python 线程池 concurrent.futures ThreadPoolExecutor 步骤: 1,导包from concurrent.futures import ThreadPoolEx ...
- Python线程池与进程池
Python线程池与进程池 前言 很多人学习python,不知道从何学起. 很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手. 很多已经做案例的人,却不知道如何去学习更加高深的知识 ...
- python线程池(threadpool)模块使用笔记详解
这篇文章主要介绍了python线程池(threadpool)模块使用笔记详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考.一起跟随小编过来看看吧 最近在做一个视频设备管理的项目,设备包括(摄像 ...
- python线程池使用和问题记录
记录一次使用多线程的问题 背景 最近工作有个需求根据文件中的数据请求中台服务,然后解析返回值.文件中每行代表一个参数,使用post方式携带参数请求中台接口. 分析:需要处理的数据量非常大(近200w行 ...
- 浅谈python线程池
python线程池的使用 python的多线程管理一直很麻烦,可能是我基础不够好,这里记录并分享以下python的线程池管理 在网上查了一个线程池的使用资料,个人感觉不是很清晰 但是重点很到位, 原文 ...
- python线程池wait_python线程池 ThreadPoolExecutor 的用法示例
前言 从Python3.2开始,标准库为我们提供了 concurrent.futures 模块,它提供了 ThreadPoolExecutor (线程池)和ProcessPoolExecutor (进 ...
- python3 线程池源码解析_5分钟看懂系列:Python 线程池原理及实现
概述 传统多线程方案会使用"即时创建, 即时销毁"的策略.尽管与创建进程相比,创建线程的时间已经大大的缩短,但是如果提交给线程的任务是执行时间较短,而且执行次数极其频繁,那么服务器 ...
最新文章
- mysql数据库事务日志已满_服务器事务日志已满解决方法
- 适用于VS C++环境的注释代码段,可以让你的代码被使用时有高可读性的注释
- NameNode 启动失败 - There appears to be a gap in the edit log. We expected txid xxx, but got tx
- 【Python】Python第三方库安装
- UML类图介绍及简单用法
- OpenStack搭建glance
- matlab遗传算法工具箱的设计,MATLAB遗传算法工具箱的设计
- RoboWare 下载地址
- 【零基础】计算机网络技术基础与就业前景
- wincc怎么c语言编程,WINCC几个常用C语言编程
- 计算机的平方根的符号是哪个,平方根
- 恩与爱是扯不开的 —— 李安
- vue即时通讯,一个很好用的插件
- linux 挂载3t硬盘分区,Ubuntu挂载3T硬盘或大于2T磁盘的方法
- 樊登36个问题建立亲密关系_拉近亲密关系的36个问题
- 迎接第五次工业革命浪潮,不当纳米知识文盲
- ​Hello Qt(四十七)——QtQuick基础​
- 莫队-一个让查询的高效的方法-并不深刻的讲解文章-但是易懂!
- 关于计算机固态硬盘正确的是,SSD的不正确使用说明,建议你们不要打开
- arduino中Keypad 库函数介绍
热门文章
- 统计学概览与统计检验总结
- Optic Disc Detection using Template Matching based on Color Plane Histograms
- 论文笔记:CQR-SQL: Conversational Question Reformulation Enhanced Context-Dependent Text-to-SQL Parsers
- 局域网内不定期拷贝文件到所有机器上怎么实现?
- android 最新头条适配,android 平板适配,今日头条适配(同时适配手机和平板)
- Linux15 --- 信号量、ipcs
- 每天5分钟,细读PHP手册-14
- selinux移植调试记录
- cobar文档 - 资料集合
- I2C通信与解码笔记