2017-02-09 112 views
0

事情是我想殺死當前正在運行的所有線程。例如,我有一個按鈕,它調用了for循環。突然間我想阻止它。python線程以最好的方式終止或終止

這裏是我的代碼:

class WorkerThread(threading.Thread): 
    def __init__(self,t,*args): 
     super(WorkerThread,self).__init__(target=t,args=(args[0],args[3])) 
     self.start() 
     self.join() 

我的實現:

def running(fileopen,methodRun): 
    #....long task of code are here... 


for file in fileTarget: 
     threads.append(WorkerThread(running,file,count,len(fileTarget),"FindHeader")) 
+0

設置鎖定線程的執行單元,不久以後,您可以更改標誌的狀態,讓線程完成其運行一個布爾標誌方法乾淨.... –

+0

嗨,先生,謝謝你的建議,你可以顯示一些代碼來處理? 2到4行代碼將會執行。 – iamcoder

+3

[有什麼辦法可以殺死Python中的線程?](http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python) –

回答

1

切勿突然終止線程。而不是在你的WorkerThread類中設置一個標誌/信號,然後當你希望它停止時只設置標誌並使線程自行完成。

另外你對如何子類threading.Thread產生誤解。如果你決定運行功能的線程,它應該是:

thread = threading.Thread(target=my_func, args=(arg1, arg2...)) 
thread.start() 

那麼,在你的情況下,這不會因爲你想要的線程停止請求時,適合您的需求。因此,現在讓我們子類threading.Thread,基本上__init__就像python中的構造函數,每次創建實例時它都會被執行。然後你立即start()線程,然後用join()阻止它,它的作用是在你的for循環中threads.append(WorkerThread(running,file,count,len(fileTarget),"FindHeader"))將會阻塞,直到running的末尾完成file,然後繼續與另一個file一起工作,沒有實際的線程被使用。

你應該將你的running(fileopen,methodRun)run()

class WorkerThread(threading.Thread): 
    def __init__(self,*args): 
     super(WorkerThread,self).__init__() 
     self.arg_0 = arg[0] 
     self.arg_1 = arg[1] 
     ... 
     self.stop = False 

    def run(self): 
     # now self.arg_0 is fileopen, and self.arg_1 is methodRun 
     # move your running function here 
     #....long task of code are here... 

     Try to do self.stop check every small interval, e.g. 

     ... 

     if self.stop: 
      return 

     ... 



for file in fileTarget: 
    new_thread = WorkerThread(file, count, len(fileTarget), "FindHeader")) 
    new_thread.start() 

    threads.append(new_thread) 

# Stop these threads 
for thread in threads: 
    thread.stop = True