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

2024-04-20 10:46:04 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: inimportfortimemaindefdoconcurrent