当一个Python并发的将来对象完成时,如何不轮询而停止主线程?

问题描述

我有一个函数,它使用concurrent.futures.ThreadPoolExecutor在运行另一个函数时显示进度条。

def run_with_loading(function,args=[],kwargs={},phrase="Loading...",bar_length=5):
    '''
    Run a function while showing a loading bar.
    '''
    with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
        f = executor.submit(function,*args,**kwargs)
        while True:
            for i in range(bar_length):
                if f.done():
                    result = f.result()
                    if f.exception() or not result[0]:
                        c = "✗"
                    else:
                        c = "✔"
                    print(f"\33[2K\r{phrase} {c}")
                    return result
                sys.stdout.write(
                    f"\r{phrase} {'□' * i}{'■'}{'□' * (bar_length - i - 1)}")
                sys.stdout.flush()
                time.sleep(0.2)

但是,它仍然轮询每隔0.2秒查看一次功能是否完成。在此有效的同时,我想知道是否有更有效的方法来通知run_with_loading函数启动的function已完成。我需要保留是否有异常,这在代码中已明确说明,以便可以打印

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)