python线程池回调函数_python 简单线程池使用

一、安装与简介

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值