concurrent.futures 学习笔记


concurrent.futures

先看下官方介绍

The asynchronous execution can be performed with threads, using ThreadPoolExecutor, or separate processes, using ProcessPoolExecutor. Both implement the same interface, which is defined by the abstract Executor class.

重点是 asynchronous

concurrent.futures._base.Executor

submit(fn, *args, **kwargs) -> Future

with ThreadPoolExecutor(max_workers=1) as executor:
    future = executor.submit(pow, 323, 1235)
    print(future.result())

map(func, *iterables, timeout=None, chunksize=1) -> typing.Generator

类似于 map(内置函数)

In [26]: def test(item):
    ...:     print("echo", item)
    ...:     return item
    ...:
In [27]: list(map(test, range(10)))
echo 0
echo 1
echo 2
echo 3
echo 4
echo 5
echo 6
echo 7
echo 8
echo 9
Out[27]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  • demo
def test(item):
    print(f"echo {item}")
    return item
with ThreadPoolExecutor(max_workers=1) as executor:
    future = executor.map(test, range(3))

shutdown

# todo

ThreadPoolExecutor

  • 注意避免在一个 Future 里面获取另外一个 Future 的 result

ProcessPoolExecutor

在 IO 密集型下使用 ThreadPoolExecutor

Future

  • cancel()
    • 无法取消当前正在执行的
  • result() -> bool
  • running() -> bool
  • done() -> bool
  • result(timeout=None) -> Any
  • exception(timeout=None) -> Exception
exector = ThreadPoolExecutor(max_workers=10)
f: Future = exector.submit(test, 1)
exception: Exception = f.exception(timeout=None)
  • add_done_callback(fn) -> None
def callback(*args):
    print(args) # (<Future at 0x102bcb898 state=finished raised KeyError>,) 即 f


exector = ThreadPoolExecutor(max_workers=10)
f: Future = exector.submit(test, 1)
f.add_done_callback(callback)
优质内容筛选与推荐>>
1、Javascript中call()和apply()的用法 ----2
2、IOS在不同的uiview中传递参数
3、C#设计模式--代理模式
4、phpcmsv9后台模板_MunSkin+v1.2+by+蒙奇时光
5、Discuz!x2 康盛创想 Windows (server 2003) 服务器部署标准


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号