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()
为什么脚本会死掉,除非我添加一会儿True:睡眠在main()中? (线程1和线程2都具有永远运行的功能) daemon = 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()
答案 0 :(得分:1)
这是Python issue 18966;在关闭之前,多处理进程没有join
非守护进程线程。该行为已在Python 3.7.0中更改,因此现在可以join
处理其非守护进程线程。