您的当前位置:首页正文

python怎样终止线程

2024-07-17 来源:好兔宠物网

在python中启动和关闭线程:

一、启动线程

首先导入threading

import threading

然后定义一个方法

    def serial_read():
   		...
   		...

然后定义线程,target指向要执行的方法

myThread = threading.Thread(target=serial_read)

启动它

myThread.start()

二、停止线程

import inspect
import ctypes
def _async_raise(tid, exctype):
    """raises the exception, performs cleanup if needed"""
    tid = ctypes.c_long(tid)
    if not inspect.isclass(exctype):
        exctype = type(exctype)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # """if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread):
    _async_raise(thread.ident, SystemExit)

停止线程

stop_thread(myThread)

stop方法可以强行终止正在运行或挂起的线程。

推荐学习《》

好兔宠物网还为您提供以下相关内容希望对您有帮助:

python中如何中止一个线程

简单来说,它kill的原理是设置一个flag位,然后线程在执行下一句python语句检测到这个位被设置了之后,就会自行退出,以达到kill的目的。另外还有一种更容易理解的flag置位的实现方式:classKillableThread(threading.Thread):def__init__(self):threading.Thread.__init__(self)self.stop = Falsedefrun(...

Python里如何终止一个线程

Python用sleep停止一个线程的运行,而不影响主线程的运行,案例代码如下:from threading import *import timeclass MyThread(Thread): def run (self): self.ifdo = True; while self.ifdo: print 'I am running...' time.sleep(2) def stop (self): print 'I am sto...

Python中怎么在终止一个线程的同时终止另外一个线程?

在每个子线程中,循环检测全局变量的值,当检测到值为True时退出线程函数。

求助python多线程,执行到100多个停止了

def pause(self):self.__flag.clear() # 设置为False, 让线程阻塞 def resume(self):self.__flag.set() # 设置为True, 让线程停止阻塞 def stop(self):self.__flag.set() # 将线程从暂停状态恢复, 如何已经暂停的话 self.__running.clear() # 设置为False 下面是测试代码:a ...

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的问题.怎么终止一个子线程

等待串口数据导致线程自己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 s...

python 怎么杀死指定线程名的线程

1、在主进程执行,调用一个进程执行函数,然后主进程sleep,等时间到了,就kill 执行函数的进程。测试一个例子:[python] view plain copy import time import threading def p(i):print i class task(threading.Thread):def __init__(self,fun,i):threading.Thread.__init__(self)self.fun = ...

python线程怎么销毁

elif self.thread_name == "线程3":ticket_for_thread3 += 1;elif self.thread_name == "线程4":ticket_for_thread4 += 1;else:break;仅能有一个线程↑↑↑ mutex_lock.release(); # 临界区结束,互斥的结束 mutex_lock.release(); # python在线程死亡的时候,不会清理已存在在线程...

如何终止一个bottle 线程 python

通常运行的时候,程序一开始就会提示“Hit CTRL-C to quite”,按照字面上意思,Contrl+C退出就行了。如果你用了Gunicorn之类的WSGI HTTP服务器来并发Bottle的话,那么把Gunicorn进程结束掉就好了。如果是用python的multiprocessing弄出来的bottle服务进程,那么在需要结束的地方先.join()。

Python主线程结束为什么守护线程还在运行

法很多。通常的法是,子线程出异常后,主进程检查到它的状态不正常,然后自己主动将其余线程退出,最后自己再退出。这是稳妥的法。另外的法是,某一个子线程专用于监控状态。它发现状态不对时,直接强制进程退出。法1,发消息给主进程,让主进程退出。法2:用kill,pskill等方法,直接按进程PID杀进程。