使用python多处理库,让父进程先于子进程返回



当从python创建具有多处理库的进程时,父进程会等待其子进程返回,然后再返回。事实上,该文件建议加入所有儿童。但我想让父进程在其子进程结束之前返回

是否有任何方法可以"分离"子进程。

我知道使用子流程。Popen可以创建分离的子进程,但我想使用多处理库中的功能,如队列、锁等

我举了两个例子来说明区别。

第一个示例使用多处理库。当调用此脚本时,它会打印父消息,等待5秒,打印子消息,然后返回。

# Using multiprocessing, only returns after 5 seconds
from multiprocessing import Process
from time import sleep, asctime
def child():
    sleep(5.0)
    print 'Child end reached on', asctime()
if __name__ == '__main__':
    p = Process(target = child)
    p.start()
    # Detach child process here so parent can return.
    print 'Parent end reached on', asctime()

第二个示例使用子流程。波本。当调用此脚本时,它将打印父消息,返回(!!!),并在5秒钟后打印子消息。

# Using Popen, returns immediately.
import sys
from subprocess import Popen
from time import sleep, asctime
def child():
    sleep(5)
    print 'Child end reached on', asctime()
if __name__ == '__main__':
    if 'call_child' in sys.argv:
        child()
    else:
        Popen([sys.executable] + [__file__] + ['call_child'])
        print 'Parent end reached on', asctime()

如果我可以传递Queues、Pipes、Locks、Semaphores等,那么第二个例子是可以接受的

IMO,第一个例子也导致了一个更干净的代码。

我在Windows上使用python 2.7。

只需将流程对象从当前流程对象的_children集中移除,父流程就会立即退出。

h多处理模块管理私有集中的子进程,并在当前进程退出时加入它们。如果你不关心孩子,你可以把他们从片场带走。

process = multiprocessing.Process(target=proc_main)
multiprocessing.current_process()._children.discard(process)
exit(0)

最新更新