不阻塞父进程的Python多进程



我正在尝试创建一个简单的应用程序,它可以连续监视收件箱,然后在对收到的邮件进行分类后调用各种函数作为子进程。

我希望父进程继续它的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()

如上所述,一个函数不应该有多个并发子进程实例,但是如果进程在运行不同的函数,它们可以并发运行。

这可以用多处理包做吗?

继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()

您可以使用两个队列,一个用于Type1的邮件,一个用于Type2的邮件,还有两个进程,一个用于Type1的邮件,一个用于Type2的邮件。

首先创建这些队列。然后创建进程,并将第一个队列分配给第一个进程,将第二个队列分配给第二个进程。两个Process对象都需要一个参数target,这是Process执行的函数。根据逻辑,您可能需要两个函数(同样,每种类型一个函数)。在函数内部,你想要一个像无限循环的东西,从队列(即邮件)中获取项目,然后根据你的逻辑对它们采取行动。main函数还将包含一个无限循环,在此循环中检索邮件,并根据邮件的类型将其放置在正确的Queue中。

所以在主循环之前启动两个进程,然后启动主循环,邮件应该放在队列上,在子进程中被拾取。

最新更新