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






  • 相关阅读:
    选择LDO的方法(转)
    详细讲解MOSFET管驱动电路(转)
    队列--参考源码(转)
    锂电池保护板原理(转)
    低电压锁定(UVLO) (转)
    i2c的时钟延展问题(转)
    I2C死锁原因及解决方法(转)
    记录cocos2d-x3.0版本号更改内容官方说明
    c#面试题总结
    【面试】【Spring常见问题总结】【07】
  • 原文地址:https://www.cnblogs.com/ydf0509/p/7611885.html
Copyright © 2011-2022 走看看