2015-09-15 118 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