python如何关闭线程
python关闭线程的方法:首先导入threading,定义一个方法;然后定义线程,target指向要执行的方法,启动它;最后停止线程,代码为【stop_thread(myThread)】。
本教程操作环境:windows7系统、python3.9版,DELL G3电脑。
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)
-
mail.ru是什么邮箱 mail.ru邮箱登录入口 时间:2025-09-10
-
输入gpedit.msc找不到文件的原因及解决方案 时间:2025-09-10
-
nrg是什么格式文件?nrg文件用什么打开? 时间:2025-09-10
-
JavaScript中removeChild删除所有子节点方法详解(附代码) 时间:2025-09-10
-
Java运行时异常(RuntimeException)的原因及解决办法 时间:2025-09-10
-
PHP中随机数生成的方法有哪些(生成随机数的函数) 时间:2025-09-10
今日更新
-
通天排屋梗揭秘:网络热词背后的幽默文化解析
阅读:18
-
通讯兵的梗是什么梗?揭秘战场传令兵爆笑日常,看完笑到信号中断!
阅读:18
-
逆水寒手游社交能量怎么刷-社交能量获取
阅读:18
-
如鸢九月洞窟懒人版-戏学核爆与二星徐庶怎么过
阅读:18
-
最终幻想14新版本9月11日将更新-全新副本来袭
阅读:18
-
世界之外9月10日夏萧因生日更新公告完整版
阅读:18
-
闪暖×开心消消乐联动活动-9月12日更新后开启
阅读:18
-
明日之后感染者驱逐行动明日开启-珍贵奖励惊喜兑换
阅读:18
-
通讯兵梗源自军事幽默 指传递消息时总爱添油加醋的队友 网友调侃现代版传话游戏 笑点在于信息越传越离谱
阅读:18
-
原神月之一版本空月之歌呈示更新公告-完整版公告
阅读:18