我只是对我编写的一些代码感到非常困惑。我惊讶地发现:
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
results = list(executor.map(f, iterable))
和
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
results = list(map(lambda x: executor.submit(f, x), iterable))
产生不同的结果。第一个生成一个f
返回任何类型的列表,第二个生成一个concurrent.futures.Future
对象列表,然后需要使用它们的result()
方法评估这些对象以获得f
返回的值。
我主要担心的是这意味着executor.map
不能利用concurrent.futures.as_completed
,这似乎是一种非常方便的方法来评估我正在对数据库进行的一些长期运行调用的结果,因为它们变得可用。
我完全不清楚concurrent.futures.ThreadPoolExecutor
对象是如何工作的——天真地,我更喜欢(有点冗长):
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
result_futures = list(map(lambda x: executor.submit(f, x), iterable))
results = [f.result() for f in futures.as_completed(result_futures)]
更简洁executor.map
,以便利用可能的性能增益。我这样做有错吗?