Te11UA
V2EX  ›  Python

用 ThreadPoolExecutor 时如何同时 submit 和 as_completed?

By Te11UA at 2020 年 7 月 11 日 · 2238 次点击

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

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 方法?

第 1 条附言  ·  2020 年 7 月 12 日
最后看了还是使用 Queue 解决了 ~
2 条回复  •  2020-07-12 02:36:55 +08:00
ClericPy
   1
ClericPy  
   2020 年 7 月 11 日
executor.submit 会生产一个在运行的 Future

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

所以, 理论上来说, 你那个情景类似生产者消费者了, 该走的是队列而不是 as_completed
laike9m
   2
laike9m  
   2020 年 7 月 12 日
两个线程没啥问题
推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
© 2026 V2EX · 25ms · 3.9.8.5