我有这样的代码: 很明显,“完成”已被打印出来。但是加入仍然是障碍。 为什么会发生这种情况?
from multiprocessing import Process
class MyProcess(Process):
def run(self):
## do someting
print 'finished'
processes = []
for i in range(3):
p = MyProcess()
p.start()
processes.append(p)
for p in processes:
p.join()
答案 0 :(得分:1)
您应添加此行if __name__ == '__main__':
,以使事情正常运行
说明:
您的主脚本将通过process.py
模块导入,然后它将执行您的脚本行2次,一次是在导入过程中,另一次是从脚本执行中完成,
如果我们不包含if __name__ == '__main__':
RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
This probably means that you are not using fork to start your
child processes and you have forgotten to use the proper idiom
in the main module:
if __name__ == '__main__':
freeze_support()
...
The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce an executable.
您在python 3.6中的工作代码是:
from multiprocessing import Process
class MyProcess(Process):
def run(self):
## do someting
print ('finished')
processes = []
if __name__ == '__main__':
for i in range(3):
p = MyProcess()
p.start()
processes.append(p)
for p in processes:
p.join()
print('we are done here .......')
输出:
finished
finished
finished
we are done here .......
答案 1 :(得分:0)
join
不会在任务完成时阻止,而且您的程序无效。
for i in 3: # X integer is not iterable,
for i in range(3): # should be like this.