首页 > 解决方案 > 如何在python3多处理中保持没有“主线程”的进程?

问题描述

python中的多处理启动了一个新进程。

在那个新进程中,我创建了 2 个新线程,并且在启动新进程的“主线程”中什么也不做,似乎该进程已经消失了。

例子:

new_process = multiprocessing.Process(target=new_proc_main, name=yyy)
new_process.start()

def new_proc_main():
    thread1 = threading.Thread(target=xxxx, name=thread1)
    thread1.start()
    thread2 = threading.Thread(target=xxxx, name=thread2)
    thread2.start()

如何在线程 1 和 2 运行时保持新进程处于活动状态?

标签: python-3.xpython-multiprocessing

解决方案


我写了一个测试程序。这是 MacOS 上的 Python 3.6.2

import multiprocessing
import time

def new_main():
    import threading
    my_thread = threading.Thread(target=dummy_main)
    my_thread.start()
    my_thread.join()

def dummy_main():
    while True:
        print("thread running")
        time.sleep(1)

print("start process")
p = multiprocessing.Process(target=new_main)
p.start()

关键是我必须有my_thread.join()。如果我没有,程序会立即退出。


推荐阅读