python concurrent.futures包使用,捕获异常
2024-10-19 04:35:10
concurrent.futures的ThreadPoolExecutor类暴露的api很好用,threading模块抹油提供官方的线程池。和另外一个第三方threadpool包相比,这个可以非阻塞的运行主进程(前提是自己不主动调用shutdown(Tuue))。
这个包在py3种已经是官方自带了。py2种需要自己安装, pip install futures # coding=utf-8
import time
from concurrent.futures import ThreadPoolExecutor
from Logger import Logger
lg=Logger(logname='log4.txt', loglevel=1, logger="concurrent.futures").getlog()
def fun(strx):
time.sleep(2)
print y
print strx def callbackx(rst):
rst.result() threadPoolExecutor=ThreadPoolExecutor(3)
for i in range(20):
futurex=threadPoolExecutor.submit(fun,'hello')
futurex.add_done_callback(callbackx) print 'over'
ThreadPoolExecutor类暴露3个方法是map、submit、shutdown
map传参是一个可迭代的
例如,如果不使用 submit可以这样
threadPoolExecutor.map(fun,['hello']*20) shutdown方法作用
"""Clean-up the resources associated with the Executor. It is safe to call this method several times. Otherwise, no other
methods can be called after this one. Args:
wait: If True then shutdown will not return until all running
futures have finished executing and the resources used by the
executor have been reclaimed.
"""
def shutdown(self, wait=True):方法接受两个参数,第二个参数设置成true那么最后一行的print 'over'会在所有hello打印完成后才打印,设置成false会使所有线程没运行完就打印。
关闭后,就不能在使用这个对象submit 或者map其他方法了。
fun函数里面故意写了个print y,y是没定义的,如果不设置回调函数并且捕获日志,是看不到任何错误提示的。 所以要使用回调,并且捕获名为concurrent.futures的log,才能显示出错误。 所以使用这个包时候,一定要设置回调,在回调函数中使用回调结果的result()方法,并且设置捕获日志,否则你函数中一大堆错误,啥都不提示,你还以为代码没毛病呢。
最新文章
- 记录分享公司Spring data相关配置
- maven权威指南学习笔记(一)——简介
- 1Z0-053 争议题目解析701
- mysql数据库链接与创建
- linux的sysctl基本配置
- 【bzoj3160】万径人踪灭 FFT
- 项目中使用oracle序列
- java.lang.IllegalStateException: getWriter() has already been called for this response问题解决
- HDU5596/BestCoder Round #66 (div.2) 二分BIT/贪心
- hotfix分析
- ASP.NET中页面加载时文本框(texbox控件)内有文字获得焦点时文字消失
- poj 3783 Balls 动态规划 100层楼投鸡蛋问题
- DataGridView绑定BindingList<;T>;带数据排序的类
- LFS,编译自己的Linux系统 - 编译临时系统
- freemarker写select组件(二十二)
- OpenGL鼠标拖拽
- URL 规范 整理
- 4.Python3运算符
- python魔法方法:__getattr__,__setattr__,__getattribute__
- Google 新实现的Protobuf RPC: grpc