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


最新文章

  1. 记录分享公司Spring data相关配置
  2. maven权威指南学习笔记(一)——简介
  3. 1Z0-053 争议题目解析701
  4. mysql数据库链接与创建
  5. linux的sysctl基本配置
  6. 【bzoj3160】万径人踪灭 FFT
  7. 项目中使用oracle序列
  8. java.lang.IllegalStateException: getWriter() has already been called for this response问题解决
  9. HDU5596/BestCoder Round #66 (div.2) 二分BIT/贪心
  10. hotfix分析
  11. ASP.NET中页面加载时文本框(texbox控件)内有文字获得焦点时文字消失
  12. poj 3783 Balls 动态规划 100层楼投鸡蛋问题
  13. DataGridView绑定BindingList<T>带数据排序的类
  14. LFS,编译自己的Linux系统 - 编译临时系统
  15. freemarker写select组件(二十二)
  16. OpenGL鼠标拖拽
  17. URL 规范 整理
  18. 4.Python3运算符
  19. python魔法方法:__getattr__,__setattr__,__getattribute__
  20. Google 新实现的Protobuf RPC: grpc

热门文章

  1. Android Studio 学习笔记(1)
  2. 多选下拉框带搜索(aps.net)
  3. mysql reset password重置密码
  4. [kafka] 001_kafka起步
  5. 【协议学习】SIP基本场景分析
  6. TestNG 入门指导——理解testng.xml执行/不执行某个包,某个类,某个方法
  7. Linux 常用小命令
  8. js 获取单选框和复选框的值和js dom方法给单选框和多选框赋值
  9. WEB打印大全
  10. C#的publisher与subscriber,事件发布者与订阅者