python主动杀死线程
简介
在一些项目中,为了防止影响主进程都会在执行一些耗时动作时采取多线程的方式,但是在开启线程后往往我们会需要快速的停止某个线程的动作,因此就需要进行强杀线程,下面将介绍两种杀死线程的方式。
直接强杀,通过底层c抛出异常来杀死线程
import ctypes, inspect, threading, time
def stop_thread(thread):
"""
杀死线程
:param thread:需要杀死的线程
:returns None
"""
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:
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
_async_raise(thread.ident, SystemExit)
t = None
def run():
global t
print('run start ')
count = 1
while True:
print('wait',count,'s')
time.sleep(1)
count += 1
if count == 8:
if t is not None:
stop_thread(t)
t = threading.Thread(target=run)
t.start()
t.join()
使用flag的方式,使线程跳出
此处可以直接使用一个flag,但我用了线程的event来控制线程的停止,event里面自带一个flag,默认为false,当event.set时 flag会变为true,clear则会将flag变为false,通过is_set来获取flag,isSet已经废弃。
import threading, time
class MyThread(threading.Thread):
event = threading.Event()
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
self.count = 1
def run(self):
print('MyThread start')
while True:
print(f'wait {self.count}s')
time.sleep(1)
self.count += 1
if self.event.is_set():
break
print('MyThread end')
t = MyThread(name='test')
t.start()
time.sleep(10)
t.event.set()
MyThread start
wait 1s
wait 2s
wait 3s
wait 4s
wait 5s
wait 6s
wait 7s
wait 8s
wait 9s
wait 10s
MyThread end
python主动杀死线程的更多相关文章
- python中杀死线程
有时候有这样的需要,在某种情况下,需要在主线程中杀死之前创建的某个线程,可以使用下面的方法,通过调用python内置API,在线程中抛出异常,使线程退出. import threading impor ...
- python中优雅的杀死线程
上一篇博客中,杀死线程采用的方法是在线程中抛出异常 https://www.cnblogs.com/lucky-heng/p/11986091.html, 这种方法是强制杀死线程,但是如果线程中涉 ...
- python进阶之 线程编程
1.进程回顾 之前已经了解了操作系统中进程的概念,程序并不能单独运行,只有将程序装载到内存中,系统为它分配资源才能运行,而这种执行的程序就称之为进程.程序和进程的区别就在于:程序是指令的集合,它是进程 ...
- python day 20: 线程池与协程,多进程TCP服务器
目录 python day 20: 线程池与协程 2. 线程 3. 进程 4. 协程:gevent模块,又叫微线程 5. 扩展 6. 自定义线程池 7. 实现多进程TCP服务器 8. 实现多线程TCP ...
- Python进程、线程、协程
进程和线程的解释 进程(process)和线程(thread)是操作系统的基本概念,计算机的核心是CPU,它承担了所有的计算任务: 单个CPU一次只能运行一个任务,代表单个CPU总是运行一个进程,其他 ...
- python进程、线程、协程(转载)
python 线程与进程简介 进程与线程的历史 我们都知道计算机是由硬件和软件组成的.硬件中的CPU是计算机的核心,它承担计算机的所有任务. 操作系统是运行在硬件之上的软件,是计算机的管理者,它负责资 ...
- Python进程、线程、协程详解
进程与线程的历史 我们都知道计算机是由硬件和软件组成的.硬件中的CPU是计算机的核心,它承担计算机的所有任务. 操作系统是运行在硬件之上的软件,是计算机的管理者,它负责资源的管理和分配.任务的调度. ...
- 理解 Python 中的线程
原地址:http://blog.jobbole.com/52060/ 本文由 伯乐在线 - acmerfight 翻译自 Akshar Raaj.欢迎加入技术翻译小组.转载请参见文章末尾处的要求. 我 ...
- python进阶-------进程线程(二)
Python中的进程线程(二) 一.python中的"锁" 1.GIL锁(全局解释锁) 含义: Python中的线程是操作系统的原生线程,Python虚拟机使用一个全局解释器锁(G ...
随机推荐
- brew常用命令
Homebrew 常用命令 brew -help # 查看帮助命令 brew config # 查看配置信息 brew list # 查看已安装软件包列表 brew cleanup # 清理所有包的旧 ...
- 运维:ITSM
IT服务管理(ITSM)是一套帮助企业对IT系统的规划.研发.实施和运营进行有效管理的方法,是一套方法论.ITSM起源于ITIL(IT Infrastructure Library,IT基础架构标准库 ...
- k8s docker 中部署think php 并搭建php websocket
不得不说php 对云原生有点不够友好,之前用java .net打包docker镜像 一下就ok了,php倒腾了好久才算部署成功. 场景:使用阿里云ack(k8s) 部署采用thinkPHP框架的php ...
- MySQL中读页缓冲区buffer pool
Buffer pool 我们都知道我们读取页面是需要将其从磁盘中读到内存中,然后等待CPU对数据进行处理.我们直到从磁盘中读取数据到内存的过程是十分慢的,所以我们读取的页面需要将其缓存起来,所以MyS ...
- 关于python导入数据库excel数据时出现102, b"Incorrect syntax near '.15562'.DB-Lib error message 20018, severity 1的问题总结
1.对于在使用python导入sqlsever时,出现102, b"Incorrect syntax near '.15562'.DB-Lib error message 20018, se ...
- python中collections.OrderedDict()
import collections #from collections import OrderededDict my_orderDict=collections.OrderedDict(house ...
- ElasticSearch6.4.2
做一个简单的API记录 1.依赖为6.4.2 比较老的版本 2.指定ES集群,可接多个Put(); Setting setting=Setting.builder().put("clust ...
- flowable如何适配国产数据库达梦
前言 flowable6.4.1流程引擎官方支持的数据库有:MySQL.hsql.Oracle.DB2 .postgres.SQL Server.H2.对于其他类型的数据库如何支持,尤其是国产数据库的 ...
- Visual Studio Installer下载速度为0处理办法
DNS改为:223.5.5.5即可. 223.5.5.5 下载完成后记得改回来.
- 这个Spring Security登录插件牛啊,验证码、小程序、OAuth2都能快速接入
上次我们把验证码登录.小程序登录优雅地集成到了Spring Security,很多同学大呼过瘾,相比较一些传统玩法高级了很多.胖哥就赶紧抓住机会举一反三,把几个非标准的OAuth2也接入了进来,主要是 ...