Skip to Content
流畅的Python(第2版)
book

流畅的Python(第2版)

by Luciano Ramalho
April 2023
Intermediate to advanced
769 pages
25h 16m
Chinese
Posts & Telecom Press
Content preview from 流畅的Python(第2版)
并发执行器
577
重用
flags
模块(见示例
20-2
)中的几个函数。
下载单个图像的函数。这是在各个职程中执行的函数。
实例化
ThreadPoolExecutor
,作为上下文管理器。
executor.__exit__
方法将调用
executor.
shutdown(wait=True)
,在所有线程都执行完毕前阻塞线程。
map
方法的作用与内置函数
map
类似,不过
download_one
函数会在多个线程中并发调用。
map
方法返回一个生成器,通过迭代可以获取各个函数调用返回的值——这里,每次调
download_one
返回一个国家代码。
返回获取的结果数量。如果有线程抛出异常,那么异常在
list
构造方法尝试从
executor.
map
返回的迭代器中获取相应的返回值时抛出。
调用
flags
模块中的
main
函数,传入
download_many
函数的并发版。
注意,示例
20-3
中的
download_one
函数其实是示例
20-2
download_many
函数的
for
环体。编写并发代码时经常这样重构:把依序执行的
for
循环改成函数,并发调用。
示例
20-3
特别短,因为我重用了依序下载的
flags.py
脚本中的多个函数。
concurrent.futures
最大的优势是方便在现有的依序执行代码之上添加并发
执行逻辑。
ThreadPoolExecutor
构造函数接受多个参数,这里没有用到。其中,第一个参数最为重要,
max_workers
。该参数设置最多执行多少个工作线程。
max_workers ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python高级编程(第2版)

Python高级编程(第2版)

Posts & Telecom Press, Michał Jaworski, Tarek Ziadé
Kafka权威指南(第2版)

Kafka权威指南(第2版)

Gwen Shapira, Todd Palino, Rajini Sivaram, Krit Petty
Python贝叶斯分析(第2版)

Python贝叶斯分析(第2版)

Posts & Telecom Press, Osvaldo Martin

Publisher Resources

ISBN: 9787115612366