我最近发现了Python的多重处理,所以我正在玩弄它,我跑进了一堵墙。Python多重处理拒绝循环
这是我的工作脚本:
import multiprocessing, time
def p_def():
print "running p"
time.sleep(5)
def v_def():
print "running v"
time.sleep(5)
p = multiprocessing.Process(target=p_def)
v = multiprocessing.Process(target=v_def)
while True:
time.sleep(0.25)
p.start()
while p.is_alive() == True:
time.sleep(0.5)
print "waiting for it to finish"
一切运作良好,当我运行的代码,它启动了p_def但是当它完成,并希望再次运行它,它运行到并输出我这个错误:
running p
waiting for it to finish
waiting for it to finish
waiting for it to finish
waiting for it to finish
waiting for it to finish
waiting for it to finish
waiting for it to finish
waiting for it to finish
waiting for it to finish
waiting for it to finish
Traceback (most recent call last):
File "proc.py", line 19, in
p.start()
File "/usr/lib/python2.7/multiprocessing/process.py", line 120, in start
assert self._popen is None, 'cannot start a process twice'
AssertionError: cannot start a process twice
这对我来说似乎有点奇怪。我的理解是,它应该能够再次运行它,但是,我在网上看到的是人们说它不能两次运行同样的事情。
这是怎么回事?我该如何让它运行两次?
+0
不直接相关的问题,但不是忙等待进程退出,你可以(并且可能应该)使用'p.join()'函数。 –