Python中强制终止线程的实现方法

键盘旁的猫
键盘旁的猫
发布时间:2026-10-13 | 5人浏览过
原创

本文介绍在Python中通过CTypes调用底层API来强制终止线程的方法。核心思路是利用PyThreadState_SetAsyncExc向目标线程注入异常,通常使用SystemExit。代码包含完整的线程类定义、启动、延时后强制停止及状态打印,适用于需要立即中断长时间运行线程的场景。

具体实现代码如下所示:

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 相关产品和应用

全部下载

专题列表