V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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
Te11UA
V2EX  ›  Python

用 ThreadPoolExecutor 时如何同时 submit 和 as_completed?

  •  
  •   Te11UA · 2020-07-11 21:24:00 +08:00 · 1525 次点击
    这是一个创建于 1356 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    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-07-12 09:19:40 +08:00
    最后看了还是使用 Queue 解决了 ~
    2 条回复    2020-07-12 02:36:55 +08:00
    ClericPy
        1
    ClericPy  
       2020-07-11 21:47:15 +08:00
    executor.submit 会生产一个在运行的 Future

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

    所以, 理论上来说, 你那个情景类似生产者消费者了, 该走的是队列而不是 as_completed
    laike9m
        2
    laike9m  
       2020-07-12 02:36:55 +08:00
    两个线程没啥问题
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5872 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 02:19 · PVG 10:19 · LAX 19:19 · JFK 22:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.