为什么我得不到并发执行?

Why don't I get concurrent execution?

考虑以下最小程序:

#!/usr/bin/env python3

import time
from multiprocessing import Process

def mp_test():
    time.sleep(3)
    print('mp_test')

print('start')
p = Process(target=mp_test)
p.run()
print('end')

按照我对documentation for the multiprocessing module的理解,这段代码应该mp_test()在一个单独的进程中执行,也就是说应该和主进程并行执行。因此,我希望得到以下输出:

start
end
mp_test

然而,我得到的实际输出是这样的:

start
mp_test
end

这是为什么?我需要进行哪些更改才能获得预期的结果?

尝试 p.start() 而不是 p.run()

根据文档:

In multiprocessing, processes are spawned by creating a Process object and then calling its start() method.

所以您似乎应该调用 p.start(),它会在单独的线程中依次调用 p.run(),这应该会给出您想要的结果。

调用p.run()直接跳过整个多线程位。