代码无法在python 3.8中运行多处理功能

时间:2020-05-27 22:14:33

标签: python multiprocessing

import time
import multiprocessing
start = time.perf_counter()

def do_something():
    print("Sleeping 1 second...")
    time.sleep(1)
    print("Done Sleeping...")

p1 = multiprocessing.Process(target= do_something)
p2 = multiprocessing.Process(target= do_something)

p1.start()#these should run the procesess above but do nothing
p2.start()

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

这应该打印“ Sleeping 1 seconds ...”,然后显示“ Done Sleeping ...”,但是代码完全忽略了p1.start(),仅打印了显示运行代码所花费时间的最后几行

最后我得到的是

Finished in 0.03 second(s)

1 个答案:

答案 0 :(得分:0)

从字面上复制并粘贴您的代码,它可以按预期运行。打印“睡眠1秒”,然后打印“睡眠完成”。

Finished in 0.0 second(s)
Sleeping 1 second...
Sleeping 1 second...
Done Sleeping...
Done Sleeping...

我知道您遵循本教程:https://www.youtube.com/watch?v=fKl2JW_qrso

确实是一个好人,但您还需要听他的解释。他真的很擅长。

他还解释了如何转到此输出:

Sleeping 1 second...
Sleeping 1 second...
Done Sleeping...
Done Sleeping...
Finished in 1.01 second(s)

*请注意,“完成”位于最后一行