验证as_completed,确实会等待执行,哪怕被等待的任务内部有新的任务加入。
代码如下:
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
def sleep_task(sleep_time, task_name):
print("{} sleep {} s".format(task_name, sleep_time))
time.sleep(3)
print("{} weekea {} s".format(task_name, sleep_time))
if task_name == "task3": # as_completed 会等待中途上车的任务
executor.submit(sleep_task, 6, "task4")
executor.submit(sleep_task, 20, "task5")
return task_name
executor = ThreadPoolExecutor(max_workers=2)
task1 = executor.submit(sleep_task, 2, "task1")
task2 = executor.submit(sleep_task, 3, "task2")
task3 = executor.submit(sleep_task, 3, "task3")
all_task = [task1, task2, task3]
for task in as_completed(all_task):
print(task.result(), " 执行完成")
print("main end")
结果如下:
task1 sleep 2 s
task2 sleep 3 s
task2 weekea 3 s
task3 sleep 3 s
task1 weekea 2 s
task2 执行完成
task1 执行完成
task3 weekea 3 s
task4 sleep 6 stask5 sleep 20 s
task3 执行完成
main end
task5 weekea 20 s
task4 weekea 6 s
注意 main end 输出的位置,虽然在task1,task2,task3执行完毕后就输出了,但整个程序仍旧等待了task4和task5的执行。