不阻塞父进程的Python多处理

不阻塞父进程的Python多处理,python,multiprocessing,Python,Multiprocessing,我正在尝试创建一个简单的应用程序,它可以连续监视收件箱,然后在对传入邮件进行分类后,将各种函数作为子进程调用 我希望父进程在不等待子进程完成的情况下继续while循环。 例如: def main(): while 1: checkForMail() if mail: if mail['type'] = 'Type1': process1() # '''

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

我希望父进程在不等待子进程完成的情况下继续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()
如上所述,函数的并发子进程实例不应超过一次,但是,如果进程运行不同的函数,则它们可以并发运行

这可能与多处理软件包有关吗?

您可以使用两个,一个用于类型1的邮件,一个用于类型2的邮件,另外两个用于类型1的邮件,一个用于类型2的邮件

首先创建这些队列。然后创建进程,并将第一个队列分配给第一个进程,将第二个队列分配给第二个进程。两个流程对象都需要一个参数
target
,它是流程执行的函数。根据逻辑,您可能需要两个函数(同样,每种类型一个)。在函数内部,您需要一个类似于无限循环的东西,它从队列(即邮件)中提取项目,然后根据您的逻辑对其进行操作。主要功能还包括一个无限循环,在该循环中检索邮件,并根据邮件的类型将其放置在正确的队列中


因此,在主循环之前启动两个流程,然后启动主循环,邮件应该放在队列中,在子流程中接收邮件。

根据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()