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)
-
MSBuild是什么文件夹?可以删除吗? 时间:2025-10-25 -
ntdll.dll模块错误导致程序闪退的原因及解决方法 时间:2025-10-25 -
远程桌面端口号是多少 远程桌面端口怎么修改 时间:2025-10-25 -
什么是Windows PowerShell?PowerShell是干嘛的?PowerShell窗口怎么打开? 时间:2025-10-25 -
什么是Windows Server?Windows Server和Windows的区别 时间:2025-10-25 -
.NET Framework 3.5怎么下载和安装教程 时间:2025-10-25
今日更新
-
币安与欧易C2C商家审核标准对比 哪家资质要求更严
阅读:18
-
赛博舟是什么梗?揭秘年轻人追捧的虚拟社交新潮流
阅读:18
-
币安与欧易C2C申诉处理流程对比:谁更快更透明?
阅读:18
-
币安与欧易C2C交易银行卡冻结风险对比及防范措施解析
阅读:18
-
想知道什么粥是什么梗吗?揭秘网络热梗背后有趣故事,点击了解!
阅读:18
-
币安与欧易一键买卖功能对比:哪家操作更便捷高效
阅读:18
-
"熬夜猪是什么梗?揭秘年轻人自嘲式熬夜新说法"
(符合SEO规范,含关键词"熬夜猪",疑问句式吸引点击,48字内,无符号,突出用户关心的自嘲文化)
阅读:18
-
币安与欧易C2C交易限额详解:不同KYC等级差异对比
阅读:18
-
币安与欧易对比:首次C2C交易安全教育哪家更强?
阅读:18
-
躺平主义是什么梗?揭秘年轻人拒绝内卷的新态度,轻松生活哲学引热议!
阅读:18










