python結束線程
❶ 如何控制和關閉python 線程
辦法很多。通常的辦法是,子線程出異常後,主進程檢查到它的狀態不正常,然後自己主動將其餘線程退出,最後自己再退出。這是穩妥的辦法。
另外的辦法是,某一個子線程專用於監控狀態。它發現狀態不對時,直接強制進程退出。辦法1,發消息給主進程,讓主進程退出。辦法2:用kill,
pskill等方法,直接按進程pid殺進程。
❷ Python 如何強制關閉線程
Python用sleep停止一個線程的運行,而不影響主線程的運行,案例代碼如下:
from threading import *import time class MyThread(Thread): def run (self): self.ifdo = True; while self.ifdo: print 'I am running...' time.sleep(2) def stop (self): print 'I am stopping it...' self.ifdo = False; tr = MyThread()tr.setDaemon(True)tr.start()print 'I will stop it...'time.sleep(5)tr.stop()tr.join()
❸ Python里如何終止一個線程
Python用sleep停止一個線程的運行,而不影響主線程的運行,案例代碼如下:
fromthreadingimport*
importtime
classMyThread(Thread):
defrun(self):
self.ifdo=True;
whileself.ifdo:
print'Iamrunning...'
time.sleep(2)
defstop(self):
print'Iamstoppingit...'
self.ifdo=False;
tr=MyThread()
tr.setDaemon(True)
tr.start()
print'Iwillstopit...'
time.sleep(5)
tr.stop()
tr.join()
❹ python 在線程函數中如何實現線程的暫停、恢復和終止
我們都知道python中可以是threading模塊實現多線程, 但是模塊並沒有提供暫停, 恢復和停止線程的方法, 一旦線程對象調用start方法後, 只能等到對應的方法函數運行完畢. 也就是說一旦start後, 線程就屬於失控狀態. 不過, 我們可以自己實現這些. 一般的方法就是循環地判斷一個標志位, 一旦標志位到達到預定的值, 就退出循環. 這樣就能做到退出線程了. 但暫停和恢復線程就有點難了, 我一直也不清除有什麼好的方法
❺ python編程中線程結束的問題
def _exitCheckfunc():
print "ok"
try:
while 1:
alive=False
if thread_.isAlive():
alive=True
if not alive:
break
time.sleep(1)
#為了使得統計時間能夠運行,要捕捉 KeyboardInterrupt :ctrl-c
except KeyboardInterrupt, e:
traceback.print_exc()
print "consume time :",time.time()-start
threading._shutdown=_exitCheckfunc
自己在主線程中寫一個死循環來接受ctrl+c的信號。
或者用進程監控 :
http://code.activestate.com/recipes/496735-workaround-for-missed-sigint-in-multithreaded-prog/
❻ python 如何結束子線程
等待串口數據導致線程自己sleep而沒有機會執行,主線程的join沒法繼續,方法就是這樣的,換成這個能執行
from threading import *import time class MyThread(Thread): def run (self): self.ifdo = True; while self.ifdo: print 'I am running...' time.sleep(0.1) def stop (self): print 'I will stop it...' self.ifdo = False; tr = MyThread()tr.setDaemon(True)tr.start()time.sleep(1)tr.stop()tr.join()
這樣就更直觀了
from threading import *import time class MyThread(Thread): def run (self): self.ifdo = True; while self.ifdo: print 'I am running...' time.sleep(2) def stop (self): print 'I am stopping it...' self.ifdo = False; tr = MyThread()tr.setDaemon(True)tr.start()print 'I will stop it...'time.sleep(5)tr.stop()tr.join()
❼ python里如何終止線程 比如線程里調用os.system('adb logcat')這個是不會停止的
如果直接終止線程不清楚,要不曲線下,新開啟一個進程,再得到這個進程id,然後幹掉這個進程
import
multiprocessing
def
NewProcess():
global
id
id=os.getpid()
os.system('adb
logcat')
NP=multiporcess.Process(target=one
function,args=())
NP.start()
os.kill(id,9)
❽ Python中怎麼在終止一個線程的同時終止另外一個線程
設置一個全局變數,初值為False
設置鍵盤監聽事件,當監測到特定按鍵時,將全局變數的值修改為True
在每個子線程中,循環檢測全局變數的值,當檢測到值為True時退出線程函數。
❾ python 主程序結束的時候線程是否結束問題2個問題
第一個問題:因為主進程已經結束,相關的資源已經釋放,而線程還在後台運行,所以會導致線程找不到相關的資源和定義
第二個問題:因為主程序結束的時候,並沒有等待子線程結束,也沒有強制關閉子線程,因此還在後台運行,有兩個辦法可以讓他們同時結束,一個辦法是在在構建進程的時候增加參數 deamon=True, 第二個辦法就是在程序最後增加thread1.join(),thread2.join()