这是我运行的一些代码。我试图确保在我继续执行代码之前完成所有进程,但这并不像我期望的那样发生。
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
我感到困惑的是,我不希望看到“节目结束”不止一次打印,我当然不希望看到它打印出来,直到我的所有四个过程结束。我错过了什么?
答案 0 :(得分:0)
您描述的行为不会在Unix下发生,但在Windows下会发生。
Windows缺少os.fork
,因此为了启动子进程multiprocessing starts a new Python interpreter and imports the calling module。
导入时if __name__ == "__main__"
protects code from getting executed。
print('End of Program')
不在if-statement
内,每次导入调用模块时执行一次,主进程执行一次。
解决方案是简单地将print
调用放在if-statement
。