一、安装与简介
pip install threadpool
安装插件命令:python -m pip install threadpool
pool = threadpool.ThreadPool(poolsize)
requests = threadpool.makeRequests(some_callable, list_of_args, callback)
[pool.putRequest(req) for req in requests]
pool.wait()
【解析】
第一行定义了一个线程池,表示最多可以创建poolsize这么多线程;
第二行是调用makeRequests创建了要开启多线程的函数,以及函数相关参数和回调函数,其中回调函数可以不写,default是无,也就是说makeRequests只需要2个参数就可以运行;
第三行用法比较奇怪,是将所有要运行多线程的请求扔进线程池,[pool.putRequest(req) for req in requests]等同于
for req in requests:
pool.putRequest(req)
第四行是等待所有的线程完成工作后退出。
二、实际案例
import threadpool
import logging.config
logging.config.fileConfig("logger.conf")
log = logging.getLogger("logger01")
def printStr(info):
log.info("say hello " + info)
pool = threadpool.ThreadPool(5)
infolist = ['a','b','c','d']
requests = threadpool.makeRequests(printStr,infolist)
[pool.putRequest(req) for req in requests]
pool.wait()
输出结果如下:
2017-07-08 10:15:19,447 - test.py[line:15] - INFO: say hello a
2017-07-08 10:15:19,447 - test.py[line:15] - INFO: say hello b
2017-07-08 10:15:19,447 - test.py[line:15] - INFO: say hello c
2017-07-08 10:15:19,447 - test.py[line:15] - INFO: say hello d