【问题标题】:Python's ProcessPoolExecutor is giving output of print and return statement in reverse orderPython 的 ProcessPoolExecutor 以相反的顺序给出 print 和 return 语句的输出
【发布时间】:2020-07-16 00:35:52
【问题描述】:

我正在练习在 Python 中使用多处理,所以我遇到了concurrent.futures 模块。我尝试运行以下代码:

import concurrent.futures
import time


def do_something(seconds):
    print(f'Sleeping {seconds} second(s)...')
    time.sleep(seconds)
    return f'Done Sleeping for {seconds} second(s)'

def main():

    with concurrent.futures.ProcessPoolExecutor() as executor:
        results = [executor.submit(do_something, 1.5) for _ in range(2)]

        for f in concurrent.futures.as_completed(results):
            print(f.result())


if __name__ == '__main__':
    start = time.perf_counter()
    main()
    finish = time.perf_counter()
    print(f'Finished in {round(finish-start, 2)} second(s)')

我应该期待类似以下的输出:

Sleeping 1.5 second(s)...
Sleeping 1.5 second(s)...
Done Sleeping for 1.5 second(s)
Done Sleeping for 1.5 second(s)
Finished in 1.5 second(s)

但是,我得到了:

Done Sleeping for 1.5 second(s)
Done Sleeping for 1.5 second(s)
Sleeping 1.5 second(s)...
Sleeping 1.5 second(s)...
Finished in 1.83 second(s)

return 语句出现在 print 语句之前是不是很奇怪? 这是确切的片段: sublime_snip

【问题讨论】:

    标签: python python-multiprocessing


    【解决方案1】:

    这可能与标准输出缓冲有关。尝试在您的打印语句中传递flush=True,例如:

    print(f'Sleeping {seconds} second(s)...', flush=True)
    

    您可以看到这是多处理打印的一个非常常见的问题:Python multithreaded print statements delayed until all threads complete execution

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-29
      • 1970-01-01
      • 2019-06-16
      • 2019-02-25
      相关资源
      最近更新 更多