借用官网例子说明我的疑问:
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 方法?
|  |      1ClericPy      2020-07-11 21:47:15 +08:00 executor.submit 会生产一个在运行的 Future as_completed(futures) 就是一个生成器, 按照 futures 列表完成的顺序往外吐结果, 所以前提是先有这个 futures list 才能按顺序往外摘 所以, 理论上来说, 你那个情景类似生产者消费者了, 该走的是队列而不是 as_completed | 
|      2laike9m      2020-07-12 02:36:55 +08:00 两个线程没啥问题 |