用 ThreadPoolExecutor 时如何同时 submit 和 as_completed?

2020-07-11 21:24:00 +08:00
 Te11UA

借用官网例子说明我的疑问:

with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
    for future in concurrent.futures.as_completed(future_to_url):
        ...

官网的例子都是这样,将所有任务一次性放到 executor 后才使用 as_completed 判断。

如果我需要从队列中不断取任务的话,该怎么使用 as_completed 比较合适呢?

# 类似于这个意思
while True:
     executor.submit(load_url)
     time.sleep(1)

while True:
    for future in concurrent.futures.as_completed():
        #do sth...

使用两个线程?感觉在套娃……

或者说 ThreadPoolExecutor 不适用于该场景,需要自己写 threading 方法?

1536 次点击
所在节点    Python
2 条回复
ClericPy
2020-07-11 21:47:15 +08:00
executor.submit 会生产一个在运行的 Future

as_completed(futures) 就是一个生成器, 按照 futures 列表完成的顺序往外吐结果, 所以前提是先有这个 futures list 才能按顺序往外摘

所以, 理论上来说, 你那个情景类似生产者消费者了, 该走的是队列而不是 as_completed
laike9m
2020-07-12 02:36:55 +08:00
两个线程没啥问题

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/689230

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX