0
我最近發現了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 <module>
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
這對我來說似乎有點奇怪。我的理解是,它應該能夠再次運行它,但是,我在網上看到的是人們說它不能兩次運行同樣的事情。
這是怎麼回事?我該如何讓它運行兩次?
不直接相關的問題,但不是忙等待進程退出,你可以(並且可能應該)使用'p.join()'函數。 –