[英]daemon behaviour multiprocessing multithreading
from multiprocessing import Process
from threading import Thread
def main():
thread1 = myclass(varA) #subclassed threading.Thread
thread1.daemon = False
thread1.start()
thread2 = Thread(target=myfunc)
thread2.daemon = False
thread2.start()
while True:
time.sleep(1)
if __name__ == "__main__":
SUBPROCESS = Process(target=main)
SUBPROCESS.daemon = False
SUBPROCESS.start()
为什么脚本会死掉,除非我添加while True:在main()中休眠? (线程1和线程2都具有永久运行的函数)即使父进程已结束,守护进程是否也不应为False,保持活动状态(子进程和该子进程中的子线程)?
EDIT1(工作代码)(看看方法A或方法B的注释,在运行时注释其中的一部分):
from multiprocessing import Process
from threading import Thread
import time
varA = "XYZ"
class myclass(Thread):
def __init__(self, varA):
Thread.__init__(self)
self.varA = varA
def run(self):
while True:
print("myClass prints %s" %self.varA)
def myfunc():
while True:
print("myfunc prints")
def main():
thread1 = myclass(varA) #subclassed threading.Thread
thread1.daemon = False
thread1.start()
thread2 = Thread(target=myfunc)
thread2.daemon = False
thread2.start()
if __name__ == "__main__":
#METHOD A: Running as subprocess = subthreads in that subprocess will die
SUBPROCESS = Process(target=main)
SUBPROCESS.daemon = False
SUBPROCESS.start()
#METHOD B: Running as main process = subthreads in that subprocess wont die as desired
thread1 = myclass(varA) #subclassed threading.Thread
thread1.daemon = False
thread1.start()
thread2 = Thread(target=myfunc)
thread2.daemon = False
thread2.start()
这是Python问题18966 ; 关闭之前,多处理进程未join
非守护程序线程。 在Python 3.7.0中,该行为已更改,因此进程现在可以join
其非守护进程线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.