我正在尝试创建一个简单的应用程序,它持续监控收件箱,然后在对传入邮件进行分类后将各种函数作为子进程调用。
我希望父进程在不等待子进程完成的情况下继续它的 while 循环。 例如:
def main():
while 1:
checkForMail()
if mail:
if mail['type'] = 'Type1':
process1() #
'''
spawn process1, as long as no other process1 process running,
however it's fine for a process2 to be currently running
'''
elif mail['type'] = 'Type2':
process2()
'''
spawn process2, as long as no other process2 process running,
however it's fine for a process1 to be currently running
'''
# Wait a bit, then continue loop regardless of whether child processes have finished or not
time.sleep(10)
if __name__ == '__main__':
main()
如上所述,一个函数不应有多个并发子进程实例,但是如果进程运行不同的函数,它们可以并发运行。
这可能与多处理包有关吗?
答案 0 :(得分:1)
根据 pdeubel 的回答非常有帮助,完整的框架脚本如下:
<块引用>所以在主循环之前启动两个进程,然后启动主循环,邮件应该放在队列中,然后在子进程中被接收。
def func1(todo):
# do stuff with current todo item from queue1
def func2(todo):
# do stuff with current todo item from queue2
def listenQ1(q):
while 1:
# Fetch jobs from queue1
todo = q.get()
func1(todo)
def listenQ2(q):
while 1:
# Fetch jobs from queue2
todo = q.get()
func2(todo)
def main(queue1, queue2):
while 1:
checkForMail()
if mail:
if mail['type'] = 'Type1':
# Add to queue1
queue1.put('do q1 stuff')
elif mail['type'] = 'Type2':
# Add job to queue2
queue2.put('do q2 stuff')
time.sleep(10)
if __name__ == '__main__':
# Create 2 multiprocessing queues
queue1 = Queue()
queue2 = Queue()
# Create and start two new processes, with seperate targets and queues
p1 = Process(target=listenQ1, args=(queue1,))
p1.start()
p2 = Process(target=listenQ2, args=(queue2,))
p2.start()
# Start main while loop and check for mail
main(queue1, queue2)
p1.join()
p2.join()
答案 1 :(得分:0)
您可以使用两个 Queues,一个用于 Type1 的邮件,一个用于 Type2 的邮件,另外两个 Processes 一个用于 Type1 的邮件,一个用于 Type2 的邮件。
首先创建这些队列。然后创建进程并将第一个队列提供给第一个进程,将第二个队列提供给第二个进程。两个 Process 对象都需要一个参数 target
,它是 Process 执行的函数。根据逻辑,您可能需要两个函数(每种类型又一个)。在函数内部,您需要类似无限循环的东西,它从队列(即邮件)中获取项目,然后根据您的逻辑对它们采取行动。主要功能还包括一个无限循环,在该循环中检索邮件并根据它们的类型将它们放置在正确的队列中。
所以在主循环之前启动两个进程,然后启动主循环,邮件应该放在队列中,然后在子进程中被接收。