方法一、線程池執行的循環代碼為自己寫的情況
定義一個全局變量,默認為T,當QT界面關閉后,將該變量值改為F。
線程執行的循環代碼內增加一個判斷方法,每次循環之前對全局變量進行判斷,如果結果為T則進行循環、如果為F,則break退出循環,結束線程
from concurrent.futures import ThreadPoolExecutor import time a = True # 設置全局變量 def fun(): # 線程池執行的函數 while a: # 線程池中的循環代碼,每次循環都檢查一遍變量a的值 time.sleep(0.1) # 線程需要執行的具體代碼 print('1') tp = ThreadPoolExecutor(5) # 創建線程池 for i in range(10): tp.submit(fun) # 向線程池提交任務 time.sleep(1) a = False # 需要結束線程池任務時,執行該代碼 tp.shutdown() # 關閉線程池
方法二、線程池中執行的循環為調用的模塊內的方法
比如 paramiko 庫中,sftp下載文件的方法。
這種情況可以利用回調函數進行判斷。
回調函數檢查控制變量,如果檢測到需要停止執行時,執行sys.exit()結束退出線程
1 from concurrent.futures import ThreadPoolExecutor 2 import sys 3 import time 4 5 a = True 6 def call(): # 定義退出的函數 7 if not a: 8 print('線程結束退出') 9 sys.exit() # 退出 10 11 def fun(callback=None): # 模擬sftp.get方法,循環執行,並且有回調函數 12 while True: 13 time.sleep(0.1) 14 print('1') 15 if callback != None: 16 callback() # 每次循環調用回調函數,進行判斷是否需要結束線程 17 18 tp = ThreadPoolExecutor(5) 19 for i in range(10): 20 tp.submit(fun, call) 21 22 time.sleep(1) 23 a = False 24 tp.shutdown()
