Python 多处理 - 进程终止(无法启动进程两次)
Python Multiprocessing - Process Termination (cannot start a process twice)
谁能告诉我为什么下面的代码会报错"cannot start a process twice"?根据我的估计,p1 和 p2 应该已经被 p.terminate() 命令
强制关闭了
编辑:添加了更多代码以提供上下文 - 想提出一个简单的示例但省略了 while 循环
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()
谁能告诉我为什么下面的代码会报错"cannot start a process twice"?根据我的估计,p1 和 p2 应该已经被 p.terminate() 命令
强制关闭了编辑:添加了更多代码以提供上下文 - 想提出一个简单的示例但省略了 while 循环
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()