Python多处理 - 进程终止(不能启动一个进程两次)
问题描述:
谁能告诉我为什么下面的代码给出错误“无法启动一个进程两次”?根据我的估算,p1和p2应该已经被p.terminate()命令强制关闭了。编辑:在一些更多的代码中添加了上下文 - 想要拿出一个简单的例子,但忽略了while循环Python多处理 - 进程终止(不能启动一个进程两次)
import time
import os
from multiprocessing import Process
import datetime
def a():
print ("a starting")
time.sleep(30)
print ("a ending")
def b():
print ("b starting")
time.sleep(30)
print ("b ending")
morning = list(range(7,10))
lunch = list(range(11,14))
evening = list(range(17,21))
active = morning + lunch + evening
if __name__=='__main__':
p1 = Process(target = a)
p2 = Process(target = b)
while True:
while (datetime.datetime.now().time().hour) in active:
p1.start()
p2.start()
time.sleep(5)
p1.terminate()
p2.terminate()
time.sleep(5)
else:
print ("Outside hours, waiting 30 mins before retry")
time.sleep(1800)
答
它说你不能启动一个进程两次。这正是您在终止后再次拨打p1.start()
和p2.start()
时所要做的。尝试像开始时一样重新创建它们。
p1.terminate()
p2.terminate()
time.sleep(5)
p1 = Process(target = a)
p2 = Process(target = b)
p1.start()
p2.start()
+0
啊!我没有意识到你必须不断重新定义流程。我将错误“你不能重新启动一个进程”解释为“你不能重新运行已经运行的进程”,所以认为terminate()有错误。虽然我不得不反复重新定义流程,但似乎并不合乎逻辑 –
为什么两个'p1.start()'和'p2.start()'? – Arman
哦,对不起!有一个while循环封装这个在一天中的某个时间反复运行代码 –