2015-09-15 50 views

回答

0

您应在daemon财产Thread对象的,就像这样:

import threading 
import time 

def worker(): 
    while True: 
     time.sleep(1) 
     print('doing work') 

t = threading.Thread(target=worker) 
t.daemon = True 
t.start() 

编辑:要使用多个线程,你可以创建线程的列表:

my_threads = [] 
for i in range(0, 5): 
    my_threads.append(threading.Thread(target=worker)) 
    my_threads[-1].daemon = True 
2

可以传递threading.currentThread()从父节点给子线程给定的引用,并定期检查父节点是否仍然有效。

import threading 
import time 


class Child(threading.Thread): 
    def __init__(self, parent_thread): 
     threading.Thread.__init__(self) 
     #self.daemon = True 
     self.parent_thread = parent_thread 

    def run(self): 
     while self.parent_thread.is_alive(): 
      print "parent alive" 
      time.sleep(.1) 
     print "quiting" 

Child(threading.currentThread()).start() 
time.sleep(2) 

作为第二选择,你可以调用self.parent_thread.join()等待阻塞线程来完成。

https://docs.python.org/2/library/threading.html#threading.Thread.join

或者你可以在子线程设置为daemon模式,但如果只有活着守护线程的整个过程将终止。这不一定是你想要的正常关机。

https://docs.python.org/2/library/threading.html#threading.Thread.daemon