在python中实现强制关闭线程的示例
更新时间:2019年01月22日 15:24:44 作者:tian544556
今天小编就为大家分享一篇在python中实现强制关闭线程的示例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
如下所示:
import threading
import time
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)
class TestThread(threading.Thread):
def run(self):
print
"begin"
while True:
time.sleep(0.1)
print('end')
if __name__ == "__main__":
t = TestThread()
t.start()
time.sleep(1)
stop_thread(t)
print('stoped')
以上这篇在python中实现强制关闭线程的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
python学习——内置函数、数据结构、标准库的技巧(推荐)
这篇文章主要介绍了python学习——内置函数、数据结构、标准库的技巧,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-04-04
Python成功解决TypeError: ‘method’ object is
在Python编程中,有时候我们可能会遇到一个让人摸不着头脑的错误信息:TypeError: 'method' object is not subscriptable,本文给大家介绍了Python如何成功解决TypeError: ‘method’ object is not subscriptable,需要的朋友可以参考下2024-06-06
Python torch.fft.rfft()函数用法示例代码
大家应该都知道新旧版的torch中的傅里叶变换函数在定义和用法上有所不同,下面这篇文章主要给大家介绍了关于Python torch.fft.rfft()函数用法的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下2022-04-04
Python中FastAPI项目使用 Annotated的参数设计的处理方案
FastAPI 是一个非常现代化和高效的框架,非常适合用于构建高性能的 API,FastAPI 是一个用于构建 API 的现代、快速(高性能)web 框架,基于 Python 类型提示,这篇文章主要介绍了Python中FastAPI项目使用 Annotated的参数设计,需要的朋友可以参考下2024-08-08


最新评论