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()