2017-08-24 72 views
0

我在這裏的目標是讓在後臺運行的子線程,而主線程應該啓動它們,然後退出:如何退出主線程在Python,使子線程繼續在後臺

我嘗試下面的代碼:

import time 
import logging 
import threading 

logging.basicConfig(filename="threading.log",level=logging.DEBUG) 

def worker(count): 
    for c in range(count,-1,-1): 
     threadname = threading.currentThread().getName() 
     threadcount = threading.active_count() 
     threadnames = threading.enumerate() 
     logging.debug("Child thread: {} continuing with threadcount {} {} and counter value: {}".format(threadname,threadcount,threadnames,c)) 
     time.sleep(2) 

mainthread = threading.currentThread().getName() 
print ("Starting main thread:",mainthread) 
t1 = threading.Thread(target=worker,args=(10,)) 
t1.setDaemon(True) 
t1.start() 
time.sleep(5) 
print ("Attempting to close main thread:",mainthread) 

但只要主線程退出,我認爲子線程也可以退出,因爲我已經在這個threading.log輸出(這是我從孩子線程創建)

DEBUG:root:Child thread: Thread-1 continuing with threadcount 2 [<_MainThread(MainThread, started 1160)>, <Thread(Thread-1, started daemon 10232)>] and counter value: 10 
DEBUG:root:Child thread: Thread-1 continuing with threadcount 2 [<_MainThread(MainThread, started 1160)>, <Thread(Thread-1, started daemon 10232)>] and counter value: 9 
DEBUG:root:Child thread: Thread-1 continuing with threadcount 2 [<_MainThread(MainThread, started 1160)>, <Thread(Thread-1, started daemon 10232)>] and counter value: 8 

我知道使用join()不會是答案,因爲主線程會阻塞。

我不想讓主線程阻塞。

問題有解決嗎?

在此先感謝。

回答

0

你不能這樣做,這不是關於python的問題,而是關於系統的一個問題。

如果主進程退出,無論子線程還是子進程都會退出。這是由系統控制的,所以你無能爲力。

或者你可以改變主意,爲什麼你必須退出你的主流程?

0

你可以把主進程作爲一個守護進程運行,並監聽一些變量或類似的東西(你可以試試json) 如果你關閉主進程,所有其他線程等...將被關閉。

0

你應該解釋爲什麼你想要這種行爲,因爲它不應該是必要的,通過讓主線程等待join它變得休眠,不會真正消耗更多的功率/內存,如果它不在那裏。
但是t1.setDaemon(True)是什麼讓主線程停止子線程,註釋掉或刪除這一行,它應該做你想做的。但這不是好習慣。 例如:

import time 
import logging 
import threading 

logging.basicConfig(filename="threading.log",level=logging.DEBUG) 

def worker(count): 
    for c in range(count,-1,-1): 
     threadname = threading.currentThread().getName() 
     threadcount = threading.active_count() 
     threadnames = threading.enumerate() 
     logging.debug("Child thread: {} continuing with threadcount {} {} and counter value: {}".format(threadname,threadcount,threadnames,c)) 
     time.sleep(2) 

mainthread = threading.currentThread().getName() 
print ("Starting main thread:",mainthread) 
t1 = threading.Thread(target=worker,args=(10,)) 
#t1.setDaemon(True) # do not set daemon 
t1.start() 
time.sleep(5) 
print ("Attempting to close main thread:",mainthread) 
+0

你的代碼仍然使主線程等待子代碼來完成的,在我的機器。 –

+0

你如何檢查?你的意思是因爲控制檯沒有關閉?因爲其他線程仍然連接到同一個控制檯,因此它不關閉 –

相關問題