2017-04-03 79 views
0

當它被卡在while循環中時,是否可以過早地停止線程?以下是我的示例代碼,它正確運行,因爲每次調用loop_thread它都會檢查threading.Event()標誌是否已設置。當試圖運行處理信息的文件的代碼比每秒更長時,無法停止整個函數繼續執行,直到下一次迭代。例如,如果我運行dld_img_thread,則需要大約5分鐘才能完成其執行並重新檢查while循環以查看是否應繼續。我想要發生的是在短於5分鐘的時間(例如1分鐘)殺死dld_img_thread。我不在乎數據是否丟失,只是線程在函數完成執行之前停止。謝謝導致線程停留在while循環內時停止?

import threading, time, pythoncom, read_mt0 
import powerfail_debugport_reader as pf_dbg_rdr 
import powerfail_firmware_downloader as pf_fwdld 


def loop_thread(thread_name, thread_event): 
    loopCnt = 0 
    print "\nstarting {}".format(thread_name) 
    print "is {0} alive? {1}\n".format(thread_name, L00P_thread.is_alive()) 
    while not thread_event.is_set(): 
     print("value of loopCnt = {}".format(loopCnt)) 
     loopCnt += 1 
     time.sleep(1) 
    print('stopping {}\n'.format(thread_name)) 

def image_dld(thread_name, thread_event): 
    pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) 
    print "\nstarting {}".format(thread_name) 
    print "is {0} alive? {1}\n".format(thread_name, dld_img_thread.is_alive()) 
    while not thread_event.is_set(): 
     pf_fwdld.power_fail_test() 
    print('stopping {}'.format(thread_name)) 

def debug_port_thread(thread_name, thread_event): 
    pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) 
    print "\nstarting {}".format(thread_name) 
    print "is {0} alive? {1}\n".format(thread_name, debug_thread.is_alive()) 
    pf_dbg_rdr.debug_port_reader() 
    print('\nstopping {}'.format(thread_name)) 

def main(): 
    global L00P_thread, debug_thread 
    pf_dbg_rdr.samurai_event = threading.Event() 

    L00P_thread = threading.Thread(target=loop_thread, \ 
     args=('L00P_thread', pf_dbg_rdr.samurai_event)) 

    dld_img_thread = threading.Thread(target=image_dld, \ 
     args=('image_download', pf_dbg_rdr.samurai_event)) 

    debug_thread = threading.Thread(target=debug_port_thread, \ 
     args=('debug_port_reader', pf_dbg_rdr.samurai_event)) 

    L00P_thread.start() 
    dld_img_thread.start() 
    debug_thread.start() 
    debug_thread.join() 

if __name__ == '__main__': 
    main() 
    print('processes stopped') 
    print "Exiting Main Thread" 

回答

0

使用您的病情,而第二個變量一旦達到你的超時,你可以改變。

例如:

shouldRun = True 
while not thread_event.is_set() and shouldRun: 
    print("value of loopCnt = {}".format(loopCnt)) 
    loopCnt += 1 
    time.sleep(1) 
    if loopCnt > 60: shouldRun = False 

後60次迭代會停止(約60秒給你睡在每次迭代1秒)。

+0

對於循環線程來說工作正常,但對於另一個線程來說,這個過程將不起作用。我在一個外部函數中設置了一個標誌,它應該停止另一個線程,但它只會在整個函數完成執行後才起作用。 –

+0

對不起,沒有發現。我一次嘗試做太多事情是我的錯。 – peteredhead