2012-11-16 42 views
0

虽然在使用multiprocessing模块Python中的项目工作,我观察到了一些奇怪的行为。的Python:子进程退出留下它的线程运行

让我们假设我的主程序P1使用multiprocessing模块创建过程P2。该过程P2创建的线程本身叫p2_t1。有一个在P2创建这个线程之后没有代码块,所以退出(我不是调用exit,所以它只是从主返回)离开p2_t1晃来晃去。我可以在P1创建子进程的P2

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

示例代码通过strace

示例代码证实了这一点:

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_t1)的内P1创建。 P1亘古不退出,直到创建的线程p1_t1运行。

实施例的代码在这种情况下为P1

try: 
    /*do something here*/ 
except Exception,e: 
    /*create a new thread*/ 

    /*nothing here so basically process should end*/ 

在这种情况下的处理不列入出口和继续工作,直到线程正在运行。任何解释?

+0

使用反引号('\'')为行内代码,而不是大胆。 – katrielalex

+0

这不是代码,所以我想大胆的:) ..将遵守下一次 – auny

回答

0

没有任何代码来说话的,它是很难说发生了什么,但我会尝试让你的线程守护线程,然后就可以等待与P2。当胎面完成后,然后p2应该正常关闭,杀死线。事情是这样的:

t1 = threading.Thread(target=somefunc, args=((2,))) 
t1.setDaemon(True) 
t1.start() 
t1.join() 

好运,麦克

+0

示例代码准确地描述它。过程函数完全如此。我有兴趣了解其中的差异。即使其线程正在运行,子进程'p2'也能够退出。但'p1'不会退出,直到线程结束。 'p1'是我用'python myservice'启动我的程序时创建的进程。这种行为是因为python解释器调用了第一级过程吗? – auny