我在python中有一个多处理程序,它产生几个子进程并对其进行管理(如果孩子发现问题等,则重新启动它们)。每个子进程都是唯一的,它们的设置取决于配置文件。主程序的一般结构为:
def main():
messageQueue = multiprocessing.Queue()
errorQueue = multiprocessing.Queue()
childProcesses = {}
for required_children in configuration:
childProcesses[required_children] = MultiprocessChild(errorQueue, messageQueue, *args, **kwargs)
for child_process in ChildProcesses:
ChildProcesses[child_process].start()
while True:
if local_uptime > configuration_check_timer: # This is to check if configuration file for processes has changed. E.g. check every 5 minutes
reload_configuration()
killChildProcessIfConfigurationChanged()
relaunchChildProcessIfConfigurationChanged()
# We want to relaunch error processes immediately (so while statement)
# Errors are not always crashes. Sometimes other system parameters change that require relaunch with different, ChildProcess specific configurations.
while not errorQueue.empty():
_error_, _childprocess_ = errorQueue.get()
killChildProcess(_childprocess_)
relaunchChildProcess(_childprocess)
print(_error_)
# Messages are allowed to lag if a configuration_timer is going to trigger or errorQueue gets something (so if statement)
if not messageQueue.empty():
print(messageQueue.get())
有没有一种方法可以防止无限while True
循环的内容占用100pct CPU。如果我在循环结束时添加了一个睡眠事件(例如,睡眠10秒),则错误将需要10秒才能更正,ans消息将需要10秒来刷新。
如果另一方面,有一种方法可以在time.sleep()
的持续时间内拥有一个configuration_check_timer
,而如果messageQueue
或errorQueue
得到了东西,则仍在运行代码在他们里面,那太好了。