首页 > 解决方案 > 当 Python 并发未来对象完成时,如何停止主线程而不进行轮询?

问题描述

标签: pythonmultithreadingconcurrencyconcurrent.futures

解决方案


Instead of polling for the result you should use concurrent.futures.as_completed to loop through the results:

with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
    futures = []
    futures.append(executor.submit(function, *args, **kwargs))
    for future in concurrent.futures.as_completed(futures):
        result = f.result()
        if f.exception() or not result[0]:
            c = "✗"
        else:
            c = "✔"
        print(f"\33[2K\r{phrase} {c}")

You can find the documentation here: Futures doc The function as_completed an iterator to go through all finished futures, which has ended successfully.

You need to adapt your bar_length approach, but hopefully, this helps you to get another idea of how to wait for your results.


推荐阅读