下面是我运行的一些代码。我试图确保在继续我的代码之前,我的所有进程都完成了,但这并没有像我期望的那样发生。你知道吗
import sys
import multiprocessing as mp
import time
import random
def testJoin(argin):
name = mp.current_process().name
exStartTime = time.time()
time.sleep(argin * random.random())
print(name + ' took %d seconds' %(time.time() - exStartTime))
sys.stdout.flush()
if __name__ == '__main__':
instances = [10, 10, 10, 10]
jobs = []
for k in instances:
p = mp.Process(target = testJoin, args = (k,))
jobs.append(p)
p.start()
p.join()
print('End of Program')
以下是输出内容:
End of Program
Process-4 took 1 seconds
End of Program
End of Program
Process-2 took 4 seconds
End of Program
Process-1 took 9 seconds
End of Program
Process-3 took 9 seconds
我感到困惑的是,我不希望看到“程序结束”打印不止一次,我当然不希望看到它打印,直到我的四个进程都结束。我错过了什么?你知道吗
您描述的行为在Unix下不会发生,但在Windows下会发生。 Windows缺少
os.fork
,所以为了启动子进程,multiprocessing starts a new Python interpreter and imports the calling module。你知道吗导入时的
if __name__ == "__main__"
protects code from getting executed。自从不在
if-statement
内,每次导入调用模块时执行一次,主进程执行一次。你知道吗解决方案是将
print
调用放在if-statement
中。你知道吗相关问题 更多 >
编程相关推荐