我在這裏的目標是讓在後臺運行的子線程,而主線程應該啓動它們,然後退出:如何退出主線程在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()不會是答案,因爲主線程會阻塞。
我不想讓主線程阻塞。
問題有解決嗎?
在此先感謝。
你的代碼仍然使主線程等待子代碼來完成的,在我的機器。 –
你如何檢查?你的意思是因爲控制檯沒有關閉?因爲其他線程仍然連接到同一個控制檯,因此它不關閉 –