Python:子进程退出,使其线程运行

时间:2012-11-16 15:00:07

标签: python multithreading process python-multithreading

在python中使用multiprocessing模块处理项目时,我发现了一些奇怪的行为。

让我们假设我的主程序 p1 使用multiprocessing模块创建了一个 p2 进程。过程 p2 创建了一个名为 p2_t1 的线程。创建此线程后, p2 中没有代码块,因此它会退出(我不会调用exit,因此它只会从main返回),而 p2_t1 悬空。我可以通过strace

确认一下

创建子流程的 p1 中的示例代码

p = Process(target=RunService,args=(/*some args*/),name="p2")

p2 的示例代码:

def RunService():
    try:
        /*do something here*/
    except Exception,e:
        /*create a new thread*/

    /*nothing here so basically this process exits leaving the thread dangling*/

如果在 p1 中创建了一个主题(调用 p1_t1 ),则不会发生这种情况。在创建的主题 p1_t1 运行之前, p1 不会退出。

本案例中 p1

的示例代码
try:
  /*do something here*/
except Exception,e:
  /*create a new thread*/

    /*nothing here so basically process should end*/

在这种情况下,进程不会退出并继续运行,直到线程运行。有什么解释吗?

1 个答案:

答案 0 :(得分:0)

没有任何代码可以说,很难说出发生了什么,但我会尝试让你的线程成为一个守护程序线程,然后用p2等待它。当胎面完成时,p2应该正确关闭,从而消除螺纹。像这样:

t1 = threading.Thread(target=somefunc, args=((2,)))
t1.setDaemon(True)
t1.start()
t1.join()
祝你好运,迈克

相关问题