由于系统初始架构的问题,一直采用单线程运行,而当我在导入大批量数据时,要去请求大量的外部数据,使得IO一直爆满,第一反应就是使用纯种池来解决。

在网上查了一下资料,发现已经有人写了相关的应用了:
http://blog.daviesliu.net/2006/10/09/234822/
后来还发现国外一个比较完善的开源的项目:
http://chrisarndt.de/en/software/python/threadpool/

写了一段测试代码,目的是去抓一批页面过来,这些操作都被分布到50个线程当中,当然,我这种测试方法不是很准,说成是一个使用例子更合适一些,而且,如果是在IO密集型的应用中,完全可以多开几个线程:

  1. import urllib2
  2. import time
  3. import socket
  4. from datetime import datetime
  5. from thread_pool import *
  6. def main():
  7. url_list = {"sina":"http://www.sina.com.cn",
  8. "sohu":"http://www.sohu.com",
  9. "yahoo":"http://www.yahoo.com",
  10. "xiaonei":"http://www.xiaonei.com",
  11. "qihoo":"http://www.qihoo.com",
  12. "laohan":"http://www.laohan.org",
  13. "eyou":"http://www.eyou.com",
  14. "chinaren":"http://www.chinaren.com",
  15. "douban":"http://www.douban.com",
  16. "163":"http://www.163.com",
  17. "daqi":"http://www.daqi.com",
  18. "qq":"http://www.qq.com",
  19. "baidu_1":"http://www.baidu.com/s?wd=asdfasdf",
  20. "baidu_2":"http://www.baidu.com/s?wd=dddddddf",
  21. "google_1":"http://www.baidu.com/s?wd=sadfas",
  22. "google_2":"http://www.baidu.com/s?wd=sadflasd",
  23. "hainei":"http://www.hainei.com",
  24. "microsoft":"http://www.microsoft.com",
  25. "wlzuojia":"http://www.wlzuojia.com"}
  26. #使用线程池
  27. socket.setdefaulttimeout(10)
  28. print 'start testing'
  29. wm = WorkerManager(50)
  30. for url_name in url_list.keys():
  31. wm.add_job(do_get_con, url_name, url_list[url_name])
  32. wm.wait_for_complete()
  33. print 'end testing'
  34. def do_get_con(url_name,url_link):
  35. try:
  36. fd = urllib2.urlopen(url_link)
  37. data = fd.read()
  38. f_hand = open("/tmp/ttt/%s" % url_name,"w")
  39. f_hand.write(data)
  40. f_hand.close()
  41. except Exception,e:
  42. pass
  43. if __name__ == "__main__":
  44. main()

thread_pool的代码(非原创,转自:http://blog.daviesliu.net/2006/10/09/234822/)

  1. import Queue, threading, sys
  2. from threading import Thread
  3. import time
  4. import urllib
  5. # working thread
  6. class Worker(Thread):
  7. worker_count = 0
  8. timeout = 1
  9. def __init__( self, workQueue, resultQueue, **kwds):
  10. Thread.__init__( self, **kwds )
  11. self.id = Worker.worker_count
  12. Worker.worker_count += 1
  13. self.setDaemon( True )
  14. self.workQueue = workQueue
  15. self.resultQueue = resultQueue
  16. self.start( )
  17. def run( self ):
  18. ''' the get-some-work, do-some-work main loop of worker threads '''
  19. while True:
  20. try:
  21. callable, args, kwds = self.workQueue.get(timeout=Worker.timeout)
  22. res = callable(*args, **kwds)
  23. print "worker[%2d]: %s" % (self.id, str(res) )
  24. self.resultQueue.put( res )
  25. #time.sleep(Worker.sleep)
  26. except Queue.Empty:
  27. break
  28. except :
  29. print 'worker[%2d]' % self.id, sys.exc_info()[:2]
  30. raise
  31. class WorkerManager:
  32. def __init__( self, num_of_workers=10, timeout = 2):
  33. self.workQueue = Queue.Queue()
  34. self.resultQueue = Queue.Queue()
  35. self.workers = []
  36. self.timeout = timeout
  37. self._recruitThreads( num_of_workers )
  38. def _recruitThreads( self, num_of_workers ):
  39. for i in range( num_of_workers ):
  40. worker = Worker( self.workQueue, self.resultQueue )
  41. self.workers.append(worker)
  42. def wait_for_complete( self):
  43. # ...then, wait for each of them to terminate:
  44. while len(self.workers):
  45. worker = self.workers.pop()
  46. worker.join( )
  47. if worker.isAlive() and not self.workQueue.empty():
  48. self.workers.append( worker )
  49. print "All jobs are are completed."
  50. def add_job( self, callable, *args, **kwds ):
  51. self.workQueue.put( (callable, args, kwds) )
  52. def get_result( self, *args, **kwds ):
  53. return self.resultQueue.get( *args, **kwds )

引自: http://www.handaoliang.com/article_38.html

python线程池的实现相关推荐

  1. Python 线程池 ThreadPoolExecutor(二) - Python零基础入门教程

    目录 一.Python 线程池前言 二.Python 线程池 ThreadPoolExecutor 常用函数 1.线程池 as_completed 函数使用 2.线程池 map 函数使用 3.线程池 ...

  2. Python 线程池 ThreadPoolExecutor(一) - Python零基础入门教程

    目录 一.Python 线程池前言 二.Python 线程池原理 三.Python 线程池 ThreadPoolExecutor 函数介绍 四.Python 线程池 ThreadPoolExecuto ...

  3. python线程池原理及使用

    python线程池及其原理和使用 系统启动一个新线程的成本是比较高的,因为它涉及与操作系统的交互.在这种情形下,使用线程池可以很好地提升性能,尤其是当程序中需要创建大量生存期很短暂的线程时,更应该考虑 ...

  4. python 线程池 concurrent.futures ThreadPoolExecutor

    python 线程池 concurrent.futures ThreadPoolExecutor 步骤: 1,导包from concurrent.futures import ThreadPoolEx ...

  5. Python线程池与进程池

    Python线程池与进程池 前言 很多人学习python,不知道从何学起. 很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手. 很多已经做案例的人,却不知道如何去学习更加高深的知识 ...

  6. python线程池(threadpool)模块使用笔记详解

    这篇文章主要介绍了python线程池(threadpool)模块使用笔记详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考.一起跟随小编过来看看吧 最近在做一个视频设备管理的项目,设备包括(摄像 ...

  7. python线程池使用和问题记录

    记录一次使用多线程的问题 背景 最近工作有个需求根据文件中的数据请求中台服务,然后解析返回值.文件中每行代表一个参数,使用post方式携带参数请求中台接口. 分析:需要处理的数据量非常大(近200w行 ...

  8. 浅谈python线程池

    python线程池的使用 python的多线程管理一直很麻烦,可能是我基础不够好,这里记录并分享以下python的线程池管理 在网上查了一个线程池的使用资料,个人感觉不是很清晰 但是重点很到位, 原文 ...

  9. python线程池wait_python线程池 ThreadPoolExecutor 的用法示例

    前言 从Python3.2开始,标准库为我们提供了 concurrent.futures 模块,它提供了 ThreadPoolExecutor (线程池)和ProcessPoolExecutor (进 ...

  10. python3 线程池源码解析_5分钟看懂系列:Python 线程池原理及实现

    概述 传统多线程方案会使用"即时创建, 即时销毁"的策略.尽管与创建进程相比,创建线程的时间已经大大的缩短,但是如果提交给线程的任务是执行时间较短,而且执行次数极其频繁,那么服务器 ...

最新文章

  1. mysql数据库事务日志已满_服务器事务日志已满解决方法
  2. 适用于VS C++环境的注释代码段,可以让你的代码被使用时有高可读性的注释
  3. NameNode 启动失败 - There appears to be a gap in the edit log. We expected txid xxx, but got tx
  4. 【Python】Python第三方库安装
  5. UML类图介绍及简单用法
  6. OpenStack搭建glance
  7. matlab遗传算法工具箱的设计,MATLAB遗传算法工具箱的设计
  8. RoboWare 下载地址
  9. 【零基础】计算机网络技术基础与就业前景
  10. wincc怎么c语言编程,WINCC几个常用C语言编程
  11. 计算机的平方根的符号是哪个,平方根
  12. 恩与爱是扯不开的 —— 李安
  13. vue即时通讯,一个很好用的插件
  14. linux 挂载3t硬盘分区,Ubuntu挂载3T硬盘或大于2T磁盘的方法
  15. 樊登36个问题建立亲密关系_拉近亲密关系的36个问题
  16. 迎接第五次工业革命浪潮,不当纳米知识文盲
  17. ​Hello Qt(四十七)——QtQuick基础​
  18. 莫队-一个让查询的高效的方法-并不深刻的讲解文章-但是易懂!
  19. 关于计算机固态硬盘正确的是,SSD的不正确使用说明,建议你们不要打开
  20. arduino中Keypad 库函数介绍

热门文章

  1. 统计学概览与统计检验总结
  2. Optic Disc Detection using Template Matching based on Color Plane Histograms
  3. 论文笔记:CQR-SQL: Conversational Question Reformulation Enhanced Context-Dependent Text-to-SQL Parsers
  4. 局域网内不定期拷贝文件到所有机器上怎么实现?
  5. android 最新头条适配,android 平板适配,今日头条适配(同时适配手机和平板)
  6. Linux15 --- 信号量、ipcs
  7. 每天5分钟,细读PHP手册-14
  8. selinux移植调试记录
  9. cobar文档 - 资料集合
  10. I2C通信与解码笔记