在c_中,线程具有
Abort
导致
ThreadAbortException
在它们奔跑的地方被养大。python没有这个特性,所以它已经实现了。但是,此实现不会导致异常在所有异常处理结束时自动重新引发一次。
一些实验是用
sys.settrace
还有
ThreadAbortException.__del__
没有成功。对于实现一个可以自动再次引发自身的异常,这些方法似乎走在了正确的轨道上。不幸的是,一个干净的实现也可能支持未来
ResetAbort
线程的方法对我来说有点难以理解。
以下是迄今为止编写的实现:
#! /usr/bin/env python3
import ctypes
import threading
PyThreadState_SetAsyncExc = ctypes.pythonapi.PyThreadState_SetAsyncExc
PyThreadState_SetAsyncExc.argtypes = ctypes.c_ulong, ctypes.py_object
PyThreadState_SetAsyncExc.restype = ctypes.c_int
def set_async_exc(thread_id, exception):
if not isinstance(thread_id, int):
raise TypeError('thread_id should be of type int')
if not issubclass(exception, BaseException):
raise TypeError('exception should be subclass of BaseException')
return PyThreadState_SetAsyncExc(thread_id, exception)
class ThreadAbortException(SystemExit):
pass
class CThread(threading.Thread):
def abort(self):
set_async_exc(self.ident, ThreadAbortException)
我的期望是
线程异常
在它被抓获和处理之后,应该能够自动地再次提升自己。它可能需要在处理它的上下文返回给调用方之后或者在垃圾收集器收集它时引发。有人知道怎么做吗?