一、安装

pip install threadpool

二、使用介绍

(1)引入threadpool模块

(2)定义线程函数

(3)创建线程 池threadpool.ThreadPool()

(4)创建需要线程池处理的任务即threadpool.makeRequests()

(5)将创建的多个任务put到线程池中,threadpool.putRequest

(6)等到所有任务处理完毕theadpool.pool()

import threadpool
def ThreadFun(arg1,arg2):
pass
def main():
device_list=[object1,object2,object3......,objectn]#需要处理的设备个数
task_pool=threadpool.ThreadPool(8)#8是线程池中线程的个数
request_list=[]#存放任务列表
#首先构造任务列表
for device in device_list:
request_list.append(threadpool.makeRequests(ThreadFun,[((device, ), {})]))
#将每个任务放到线程池中,等待线程池中线程各自读取任务,然后进行处理,使用了map函数,不了解的可以去了解一下。
map(task_pool.putRequest,request_list)
#等待所有任务处理完成,则返回,如果没有处理完,则一直阻塞
task_pool.poll()
if __name__=="__main__":
main()

说明:makeRequests存放的是要开启多线程的函数,以及函数相关参数和回调函数,其中回调函数可以不写(默认是无),也就是说makeRequests只需要2个参数就可以运行。

二、代码实例

 
import time
def sayhello(str):
print "Hello ",str
time.sleep(2) name_list =['xiaozi','aa','bb','cc']
start_time = time.time()
for i in range(len(name_list)):
sayhello(name_list[i])
print '%d second'% (time.time()-start_time)
 

改用线程池代码,花费时间更少,更效率

 
import time
import threadpool
def sayhello(str):
print "Hello ",str
time.sleep(2) name_list =['xiaozi','aa','bb','cc']
start_time = time.time()
pool = threadpool.ThreadPool(10)
requests = threadpool.makeRequests(sayhello, name_list)
[pool.putRequest(req) for req in requests]
pool.wait()
print '%d second'% (time.time()-start_time)
 

当函数有多个参数的情况,函数调用时第一个解包list,第二个解包dict,所以可以这样:

 
def hello(m, n, o):
""""""
print "m = %s, n = %s, o = %s"%(m, n, o) if __name__ == '__main__': # 方法1
lst_vars_1 = ['1', '2', '3']
lst_vars_2 = ['4', '5', '6']
func_var = [(lst_vars_1, None), (lst_vars_2, None)]
# 方法2
dict_vars_1 = {'m':'1', 'n':'2', 'o':'3'}
dict_vars_2 = {'m':'4', 'n':'5', 'o':'6'}
func_var = [(None, dict_vars_1), (None, dict_vars_2)] pool = threadpool.ThreadPool(2)
requests = threadpool.makeRequests(hello, func_var)
[pool.putRequest(req) for req in requests]
pool.wait()
 

需要把所传入的参数进行转换,然后带人线程池。

 
def getuserdic():
username_list=['xiaozi','administrator']
password_list=['root','','abc123!','123456','password','root']
userlist = [] for username in username_list: user =username.rstrip()
for password in password_list:
pwd = password.rstrip()
userdic ={}
userdic['user']=user
userdic['pwd'] = pwd
tmp=(None,userdic)
userlist.append(tmp)
return userlist
 

扩展阅读:

Python 多进程 multiprocessing.Pool类详解

python线程池(threadpool)的更多相关文章

  1. Python之路(第四十六篇)多种方法实现python线程池(threadpool模块\multiprocessing.dummy模块\concurrent.futures模块)

    一.线程池 很久(python2.6)之前python没有官方的线程池模块,只有第三方的threadpool模块, 之后再python2.6加入了multiprocessing.dummy 作为可以使 ...

  2. python线程池--threadpool

    在爬虫时,有时候解析获得了很多图片或视频地址时,如果一个个下载完成再去下载另一个,这样执行效率太慢了,此时就可用到线程池threadpool,使用基本步骤如下: 1.定于任务函数 2.创建线程池,定义 ...

  3. 关于python线程池threadpool

    #coding=utf-8 import time import threadpool def wait_time(n): print('%d\n' % n) time.sleep(2) #在线程池中 ...

  4. python中多进程multiprocessing、多线程threading、线程池threadpool

    浅显点理解:进程就是一个程序,里面的线程就是用来干活的,,,进程大,线程小 一.多线程threading 简单的单线程和多线程运行:一个参数时,后面要加逗号 步骤:for循环,相当于多个线程——t=t ...

  5. python3 线程池-threadpool模块与concurrent.futures模块

    多种方法实现 python 线程池 一. 既然多线程可以缩短程序运行时间,那么,是不是线程数量越多越好呢? 显然,并不是,每一个线程的从生成到消亡也是需要时间和资源的,太多的线程会占用过多的系统资源( ...

  6. 自定义高级版python线程池

    基于简单版创建类对象过多,现自定义高级版python线程池,代码如下 #高级线程池 import queue import threading import time StopEvent = obje ...

  7. 线程池ThreadPool的初探

    一.线程池的适用范围 在日常使用多线程开发的时候,一般都构造一个Thread示例,然后调用Start使之执行.如果一个线程它大部分时间花费在等待某个事件响应的发生然后才予以响应:或者如果在一定期间内重 ...

  8. C#多线程学习 之 线程池[ThreadPool](转)

    在多线程的程序中,经常会出现两种情况: 一种情况:   应用程序中,线程把大部分的时间花费在等待状态,等待某个事件发生,然后才能给予响应                   这一般使用ThreadPo ...

  9. 高效线程池(threadpool)的实现

    高效线程池(threadpool)的实现 Nodejs编程是全异步的,这就意味着我们不必每次都阻塞等待该次操作的结果,而事件完成(就绪)时会主动回调通知我们.在网络编程中,一般都是基于Reactor线 ...

随机推荐

  1. Spring Cloud Config 配置中心高可用

    详细参见 <Spring Cloud 与 Docker微服务架构实战> p163-9.10 Spring Cloud Config 与 Eureka 配合使用 p163-9.12 Conf ...

  2. R-table和tapply函数

    table可统计数据的频数 tapply可根据因子.向量和要计算的函数计算 > class<-c(1,2,3,2,1,2,1,3) > class[1] 1 2 3 > c(8 ...

  3. [hadoop读书笔记] 第三章 HDFS

    P49 当数据集的大小超过一台计算机存储能力时,就有必要对数据集分区(partition)并将分区存储到若干台独立的计算机上. 管理网络中跨多台计算机存储的系统就叫分布式文件系统  Distribut ...

  4. 自然语言交流系统 phxnet团队 创新实训 个人博客 (十)

    下载emacs-23.1.tar.gz http://ftp.gnu.org/pub/gnu/emacs/emacs-23.1.tar.gz cd /opt    //cp emacs-23.1.ta ...

  5. 字节码分析finally块对return返回值的影响

    直接进入主题.看如下代码: public int test(){ int i=0; try { i=1; return i; } catch (Exception e) { i=2; return i ...

  6. android设置主mic/副mic录音

    //添加MIC设置参数 /hal/audio_extn/audio_extn.c @@ -75,6 +75,7 @@ struct audio_extn_module { bool ras_enabl ...

  7. SNMP MIB库

    -- mib文件的开头指定文件名,并且使用BEGIN开始,文件的最后用END结束 -- IMPORTS就相当与c语言中的include,包含需要使用的一些数据类型 -- 通过FROM指定引用的来源 M ...

  8. 第三百二十九节,web爬虫讲解2—urllib库爬虫—ip代理—用户代理和ip代理结合应用

    第三百二十九节,web爬虫讲解2—urllib库爬虫—ip代理 使用IP代理 ProxyHandler()格式化IP,第一个参数,请求目标可能是http或者https,对应设置build_opener ...

  9. perl学习-运算符添加引号

    这个比较有意思,在其它语言中好像没有特别提到 Perl 引号运算符如下表所示. 运算符描述实例 q{ }为字符串添加单引号q{abcd} 结果为 'abcd' qq{ }为字符串添加双引号qq{abc ...

  10. Eclipse SVN过滤文件夹及文件的方法

    有两个步骤: 1.在TortoiseSVN中将文件.文件夹加入ignore list: 2.在Eclipse中Ignored Resources利用模式匹配忽略指定文件夹.文件类型. 这样,那些无需同 ...