Python3.6环境下使用PyThreadState_SetAsyncExc抛线程异常,线程未终止问题排查
问题描述
- 运行环境为Python 3.6
- 复现基于
PyThreadState_SetAsyncExc向目标线程抛出异步异常实现线程终止的示例,代码运行后发现目标线程未按预期终止,对抛出的异常信号无响应,无法正常退出。
复现使用的源代码
# Python program raising # exceptions in a python # thread import threading import ctypes import time class thread_with_exception(threading.Thread): def __init__(self, name): threading.Thread.__init__(self) self.name = name def run(self): # target function of the thread class try: while True: print('running ' + self.name) finally: print('ended') def get_id(self): # returns id of the respective thread if hasattr(self, '_thread_id'): return self._thread_id for id, thread in threading._active.items(): if thread is self: return id def raise_exception(self): thread_id = self.get_id() res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, ctypes.py_object(SystemExit)) if res > 1: ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0) print('Exception raise failure') t1 = thread_with_exception('Thread 1') t1.start() time.sleep(2) t1.raise_exception() t1.join()
问题核心原因
- ctypes调用未做类型声明导致线程ID截断
64位系统下Python内部的线程ID是超出32位整数范围的长整数,由于代码中直接调用ctypes.pythonapi.PyThreadState_SetAsyncExc时没有明确声明函数的参数类型与返回值类型,ctypes默认会将传入的Python整数转为32位Cint类型,截断高位的线程ID,导致传入的ID与目标线程的真实ID完全不匹配。
原代码的返回值判断逻辑仅处理了返回值大于1(即异常被投递到多个线程)的异常场景,没有处理返回值为0(未匹配到任何目标线程)的场景,因此投递失败时没有任何报错输出,表现为线程无任何响应。 - 线程紧循环无GIL让出窗口
目标线程的run方法为无任何间隔的while True刷屏循环,即使线程ID传递正确,由于循环执行过密、GIL持有时间过长,解释器检查异步待处理异常的触发时机被延后,也可能导致异常迟迟无法被线程捕获执行。
修正方向
- 在调用
PyThreadState_SetAsyncExc前,补充ctypes的函数类型声明,避免ID截断:ctypes.pythonapi.PyThreadState_SetAsyncExc.argtypes = [ctypes.c_ulong, ctypes.py_object] ctypes.pythonapi.PyThreadState_SetAsyncExc.restype = ctypes.c_int - 补充返回值判断逻辑,当返回值为0时输出投递失败提示,方便定位问题。
- 在目标线程的紧循环中增加极短的休眠(如
time.sleep(0.01)),主动让出GIL,给解释器留出投递异步异常的窗口。
内容的提问来源于stack exchange,提问作者MaxM.
相关产品推荐
相关产品推荐

