[英]Python:Child process exits leaving its thread running
在使用python中的multiprocessing
模块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*/
在这种情况下,该进程不会退出并保持运行,直到线程运行为止。 有什么解释吗?
没有任何代码可言,很难说出正在发生什么,但是我会尝试将您的线程变成守护线程,然后使用p2等待它。 胎面完成后,p2应该正确关闭,从而终止螺纹。 像这样:
t1 = threading.Thread(target=somefunc, args=((2,)))
t1.setDaemon(True)
t1.start()
t1.join()
麦克,祝你好运
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.