python的processPoolexecutor以相反的顺序提供print和return语句的输出

2021-01-03 22点热度 0人点赞 0条评论
我在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)

退货声明早于打印声明是不是很奇怪?这是确切的剪报: sublime_snip

查看隐藏内容需要支付:¥1
查看

未经允许不得转载!python的processPoolexecutor以相反的顺序提供print和return语句的输出

本文地址:https://ans.52learn.online/1891

ANS52LEARN

DO BEST