python concurrent.futures包使用,捕获异常

复制代码
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()方法,并且设置捕获日志,否则你函数中一大堆错误,啥都不提示,你还以为代码没毛病呢。






posted @   北风之神0509  阅读(2157)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示