根据 thread id 停止一个线程

时间:2023-03-09 05:05:06
根据 thread id 停止一个线程

出自 https://github.com/Bogdanp/dramatiq/blob/master/dramatiq/middleware/threading.py#L62

thread_id = threading.get_ident()
 def _raise_thread_exception_cpython(thread_id, exception):
exctype = (exception if inspect.isclass(exception) else type(exception)).__name__
thread_id = ctypes.c_long(thread_id)
exception = ctypes.py_object(exception)
count = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, exception)
if count == 0:
logger.critical("Failed to set exception (%s) in thread %r.", exctype, thread_id.value)
elif count > 1: # pragma: no cover
logger.critical("Exception (%s) was set in multiple threads. Undoing...", exctype)
ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, ctypes.c_long(0))

https://docs.python.org/3/c-api/init.html#c.PyThreadState_SetAsyncExc