Python 的 ProcessPoolExecutor 以相反的顺序给出 print 和 return 语句的输出

Python's ProcessPoolExecutor is giving output of print and return statement in reverse order

我在 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

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

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

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